在聊天过程中很多时候都想要发送本界面的一张图片或者是一个表情,或者是一张相册中照片直接显示在文本框中发送出去,接下来就简单介绍一下通过UITextView
的textStorage
属性来实现这个问题;textStorage
其实是一个装载内容的容器,其里面保存的东西决定了textview的富文本显示方式.
点入UITextView
的KPI中找到textStorage
,大家可以看到@property(nonatomic,readonly,strong) NSTextStorage *textStorage NS_AVAILABLE_IOS(7_0);
再点进入NSTextStorage
可以看到NS_CLASS_AVAILABLE(10_0, 7_0) @interface NSTextStorage : NSMutableAttributedString
看到这里我们知道其实这个属性是继承自NSMutableAttributedString
我们也就不奇怪为什么其里面的内容可以决定textview的富文本排列方式;接下来看一下实现方式:
- (void)test2{
UIImageView *imgeview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"timg"]];
imgeview.frame = CGRectMake(100, 100, 100, 100);
[self.view addSubview:imgeview];
imgeview.userInteractionEnabled = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectImageTosend:)];
[imgeview addGestureRecognizer:tap];
self.textView = [[UITextView alloc]initWithFrame:CGRectMake(10, 210, 300, 100)];
self.textView.backgroundColor = [UIColor greenColor];
self.textView.font = [UIFont systemFontOfSize:17];
[_textView scrollRangeToVisible:NSMakeRange(_textView.text.length, 1)];
self.textView.delegate = self;
[self.view addSubview:self.textView];
}
-(void)selectImageTosend:(UITapGestureRecognizer *)tap{
UIImageView *imageview = (UIImageView *)tap.view;
NSTextAttachment *atacchment = [[NSTextAttachment alloc]init];
atacchment.image = imageview.image;
//图片在textview中显示的大小
atacchment.bounds = CGRectMake(0, 0, 20, 20);
NSAttributedString *attributedStr = [[NSAttributedString alloc]initWithString:@""];
attributedStr = [NSAttributedString attributedStringWithAttachment:atacchment];
//textStorage装载内容的容器,继承自NSMutableAttributedString,其里面保存的东西决定了textview的富文本显示方式
//这种方法把图片出到内容的后边,但是光标的位置不会随着内容的b改变而改变
// [self.textview.textStorage appendAttributedString:attributedStr];
[_textView.textStorage insertAttributedString: attributedStr atIndex:_textView.selectedRange.location];
_textView.selectedRange = NSMakeRange(_textView.selectedRange.location + 1, _textView.selectedRange.length);
[self resetTextStyle];
}
- (void)resetTextStyle {
NSRange wholeRange = NSMakeRange(0, _textView.textStorage.length);
[_textView.textStorage removeAttribute:NSFontAttributeName range:wholeRange];
[_textView.textStorage addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:wholeRange];
[self.textView scrollRectToVisible:CGRectMake(0, 0, _textView.contentSize.width, _textView.contentSize.height) animated:NO];
CGFloat width = CGRectGetWidth(_textView.frame);
CGSize newSize = [_textView sizeThatFits:CGSizeMake(width,MAXFLOAT)];
CGRect newFrame = _textView.frame;
CGRect maxFrame = _textView.frame;
maxFrame.size = CGSizeMake(width, maxHeight);
newFrame.size = CGSizeMake(width, newSize.height);
NSLog(@"%@",NSStringFromCGSize(newFrame.size));
}
-(void)textViewDidChange:(UITextView *)textView{
[self resetTextStyle];
}
作者:ys简单0
链接:https://www.jianshu.com/p/df1a29845440
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。