iOS UITextView 输入框
在大多数新闻类、聊天类、帖子类APP界面,都需要用户做输入操作,一般情况下,能够输入的控件,有UITextField
和UITextView
,需求就是输入框要像UITextField
一样没有输入时单行显示,又要像UITextView
一样多行输入。那么这种需求该如何实现呢?
最近整理笔记,附上以前思路和代码,不足之处还望指教
思路:
- 使用
UITextView
控件,作为输入框- 使用通知监听输入文字的改变,来计算
UITextView
显示的高度- 使用block回调输入文本和高度
- 封装成一个自定义输入控件
创建TCInputView
类,继承自UITextView
,并在.h中定义如下属性:
typedef void(^TCTextHeightChangedBlock)(NSString *text, CGFloat textHeight);
@interface TCInputView : UITextView
@property (nonatomic, copy) TCTextHeightChangedBlock textHeightChangedBlock;
@property (nonatomic, assign) NSInteger maxNumberOfLines;
@property (nonatomic, assign) NSUInteger cornerRadius;
@property (nonatomic, copy) NSString *placeholder;
@property (nonatomic, strong) UIColor *placeholderColor;
// 当文字改变时应该调用该方法
- (void)textDidChange;
@end
在.m中创建占位控件:
- (UITextView *)placeholderView {
if (!_placeholderView) {
_placeholderView = [[UITextView alloc] init];
_placeholderView.scrollEnabled = NO;
_placeholderView.showsHorizontalScrollIndicator = NO;
_placeholderView.showsVerticalScrollIndicator = NO;
_placeholderView.userInteractionEnabled = NO;
_placeholderView.font = [UIFont systemFontOfSize:17.0];
_placeholderView.textColor = [UIColor lightGrayColor];
_placeholderView.backgroundColor = [UIColor clearColor];
}
return _placeholderView;
}
在- init()初始化方法中注册通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
监听文本输入框的改变,并调用block,回调文字和高度,其实核心代码也在于此:
- (void)textDidChange {
self.placeholderView.hidden = self.text.length > 0;
NSInteger height = ceilf([self sizeThatFits:CGSizeMake(self.bounds.size.width, MAXFLOAT)].height);
if (self.textH != height) {
if ([UIDevice currentDevice].systemVersion.floatValue < 9.0) {
self.scrollEnabled = height > self.maxTextH && self.maxTextH > 0;
}else {
self.scrollEnabled = height > self.maxTextH && self.maxTextH > 0;
}
self.textH = height;
if (self.textHeightChangedBlock && self.scrollEnabled == NO) {
self.textHeightChangedBlock(self.text, height);
[self.superview layoutIfNeeded];
self.placeholderView.frame = self.bounds;
}else {}
}
}
这只是其中一部分关键代码,如果还有不明白的可以下载我github工程看看,如有不足之处,请指正,O(∩_∩)O谢谢!