UITextView在开发中经常用到,但一直也没对它进行正整理总结,以至于在使用的时候忽略一些小问题,还要浪费不必要的时间。
计算文本的高度和调整文本内间距
CGSize size = [textView sizeThatFits:CGSizeMake(textViewW, CGFLOAT_MAX)];
CGSize size1 = [textView.text boundingRectWithSize:CGSizeMake(textViewW, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]} context:nil].size;
NSLog(@"sizeThatFits: %f \nboundingRectWithSize: %f", size.height, size1.height);
//Output: sizeThatFits: 100.000000
//boundingRectWithSize: 83.535156
上面用两个方法计算文本高度只是为了方便比较,当然计算UITextView的高度最好的办法还是是使用sizeThatFits:
计算,它并不改变UITextView的size,它只是让UITextView根据已有文本内容和给定size计算出UITextView的contentSize。那么是什么导致两个计算高度不一致,因为textView.textContainerInset
默认值是UIEdgeInsetsMake(8, 0, 8, 0)
,设置textView.textContainerInset = UIEdgeInsetsZero
解决,再看下计算的高度值:
Output: sizeThatFits: 84.000000
boundingRectWithSize: 83.535156
计算结果基本接近,但是文本左右仍然有一定的间隔,此时可以使用lineFragmentPadding
属性,通过设置textView.textContainer.lineFragmentPadding = 0
可以去除左右间距,苹果API解释为在文本框每行的开头和结尾填充宽度默认为5,还是拿到值验证下:
CGFloat lineFragmentPadding = textView.textContainer.lineFragmentPadding;
UIEdgeInsets textContainerInset = textView.textContainerInset;
NSLog(@"lineFragmentPadding: %f\textContainerInset:%@", lineFragmentPadding, NSStringFromUIEdgeInsets(textContainerInset));
//Output: lineFragmentPadding: 5.000000
//textContainerInset:{8, 0, 8, 0}
占位符
第一种方法:使用将label添加在UITextView上利用delegate设置label的透明度来模仿UITextField占位符效果。这种方法使用起来虽然能达到占位占位符效果,但是多出用到UITextView时就用很多重复的代码,所以放弃使用此方法。
第二种方法:继承UITextView在其内部添加个UITextView
#import <UIKit/UIKit.h>
@interface PlaceholderTextView : UITextView
@property (nonatomic, strong) NSString *placeholder;
@property (nonatomic, strong) UIColor *placeholderColor;
@end
#import "PlaceholderTextView.h"
@interface PlaceholderTextView ()
@property (nonatomic, weak) UITextView *placeholderView;
@end
@implementation PlaceholderTextView
- (void)awakeFromNib {
[super awakeFromNib];
[self setup];
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self setup];
}
return self;
}
- (void)setup {
self.scrollEnabled = NO;
self.scrollsToTop = NO;
self.showsHorizontalScrollIndicator = NO;
self.enablesReturnKeyAutomatically = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
}
- (void)textDidChange {
self.placeholderView.hidden = self.text.length > 0;
}
- (UITextView *)placeholderView {
if (_placeholderView == nil) {
UITextField *textField = [[UITextField alloc] init];
_placeholderColor = [textField valueForKeyPath:@"_placeholderLabel.textColor"];
UITextView *placeholderView = [[UITextView alloc] init];
placeholderView.frame = self.bounds;
placeholderView.scrollEnabled = NO;
placeholderView.showsHorizontalScrollIndicator = NO;
placeholderView.showsVerticalScrollIndicator = NO;
placeholderView.userInteractionEnabled = NO;
placeholderView.font = self.font;
placeholderView.textColor = _placeholderColor;
placeholderView.backgroundColor = [UIColor clearColor];
[self addSubview:placeholderView];
_placeholderView = placeholderView;
}
return _placeholderView;
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor {
_placeholderColor = placeholderColor;
self.placeholderView.textColor = placeholderColor;
}
- (void)setPlaceholder:(NSString *)placeholder {
_placeholder = placeholder;
self.placeholderView.text = placeholder;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
第三种方法:使用UITextView的Category实现占位符效果,本来是打算自己实现的,但是在github上看到一个别出心裁的UITextView-Placeholder方法,巧妙的运用Method Swizzling、关联属性、KVO等方法实现了占位符功能,不要吝啬使用方法,推荐使用这种方法。
限制最大行数
根据行数计算出textView的最大高,每行高度 * 总行数 + 文字上下间距。
maxTextHeight = ceil(textView.font.lineHeight * maxNumberOfLines + textView.textContainerInset.top + textView.textContainerInset.bottom);
适应文字高度
- (void)textViewDidChange:(UITextView *)textView {
NSInteger height = ceilf([textView sizeThatFits:CGSizeMake(textView.bounds.size.width, MAXFLOAT)].height);
if (textHeight != height) {
textView.scrollEnabled = height > maxTextHeight && maxTextHeight> 0;
textHeight = height;
if (textView.scrollEnabled == NO) {
self.textViewConstraintH.constant = height;
[self.view layoutIfNeeded];
}
}
}
随键盘弹出效果
1、添加监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
2、处理键盘位置变化
- (void)keyboardWillChangeFrame:(NSNotification *)note {
CGRect endFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
_bottomCons.constant = endFrame.origin.y != screenH?endFrame.size.height:0;
[UIView animateWithDuration:duration animations:^{
[self.view layoutIfNeeded];
}];
}