做聊天或評論功能時,鍵盤上方那條輸入列幾乎每個專案都要寫一次。與其每次重來,不如封裝成一個可直接初始化的元件,需要調整時改屬性即可。
#import <UIKit/UIKit.h> /** 使用方式:直接初始化,或事後修改屬性 WJEasyInputTextView *wj = [[WJEasyInputTextView alloc] init]; wj.bgColor = [UIColor orangeColor]; wj.showLimitNum = YES; wj.font = [UIFont systemFontOfSize:18]; wj.limitNum = 13; [self.view addSubview:wj]; */ @interface WJEasyInputTextView : UIView @property (nonatomic, strong) UIColor *bgColor; // 背景色 @property (nonatomic, assign) BOOL showLimitNum; // 是否顯示字數 @property (nonatomic, assign) NSInteger limitNum; // 字數上限 @property (nonatomic, strong) UIFont *font; // 文字大小 @end
#import "WJEasyInputTextView.h"
@interface WJEasyInputTextView () <UITextViewDelegate>
{
UIView *_bottomView; // 輸入列容器
UITextView *_textView; // 輸入框
UILabel *_textApl; // 字數標籤
CGRect _rect; // 記錄初始 frame
}
@end
@implementation WJEasyInputTextView
- (instancetype)init
{
self = [super init];
if (self) {
self.frame = CGRectMake(0,
CGRectGetHeight([UIScreen mainScreen].bounds) - 50,
CGRectGetWidth([UIScreen mainScreen].bounds),
50);
_rect = self.frame;
[self initNotification];
[self addTextFieldComments];
}
return self;
}
#pragma mark - 初始化鍵盤監聽
- (void)initNotification
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
#pragma mark - 建立子視圖
- (void)addTextFieldComments
{
_bottomView = [[UIView alloc] initWithFrame:self.bounds];
_bottomView.backgroundColor = self.bgColor;
_bottomView.userInteractionEnabled = YES;
[self addSubview:_bottomView];
// 頂部分隔線
UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,
CGRectGetWidth(self.bounds), 0.5)];
lineView.backgroundColor = [UIColor colorWithWhite:0.6 alpha:0.3];
[_bottomView addSubview:lineView];
_textView = [[UITextView alloc] initWithFrame:CGRectMake(15, 5,
CGRectGetWidth(self.bounds) - 115, 40)];
_textView.layer.cornerRadius = 6;
_textView.layer.borderWidth = 1;
_textView.layer.borderColor = lineView.backgroundColor.CGColor;
_textView.delegate = self;
_textView.font = [UIFont systemFontOfSize:13];
_textView.autocapitalizationType = UITextAutocapitalizationTypeNone;
_textView.autocorrectionType = UITextAutocorrectionTypeNo;
[_bottomView addSubview:_textView];
// 字數標籤
_textApl = [[UILabel alloc] init];
_textApl.frame = CGRectMake(CGRectGetMaxX(_textView.frame) - 37, 35, 30, 6);
_textApl.textColor = [UIColor grayColor];
_textApl.textAlignment = NSTextAlignmentRight;
_textApl.font = [UIFont systemFontOfSize:8];
[_bottomView addSubview:_textApl];
// 發送按鈕
UIButton *plBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
plBtn.layer.borderWidth = 1;
plBtn.layer.cornerRadius = 6;
plBtn.layer.borderColor = lineView.backgroundColor.CGColor;
plBtn.backgroundColor = [UIColor whiteColor];
[plBtn setTitle:@"發送" forState:UIControlStateNormal];
[plBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
plBtn.frame = CGRectMake(CGRectGetMaxX(_textView.frame) + 10,
CGRectGetMinY(_textView.frame),
80, CGRectGetHeight(_textView.frame));
[plBtn addTarget:self action:@selector(pinglun)
forControlEvents:UIControlEventTouchUpInside];
[_bottomView addSubview:plBtn];
}
#pragma mark - setter
- (void)setBgColor:(UIColor *)bgColor
{
_bgColor = bgColor;
_bottomView.backgroundColor = bgColor;
}
- (void)setLimitNum:(NSInteger)limitNum
{
_limitNum = limitNum;
_textApl.text = [NSString stringWithFormat:@"%ld", (long)limitNum];
}
- (void)setShowLimitNum:(BOOL)showLimitNum
{
_showLimitNum = showLimitNum;
_textApl.hidden = !showLimitNum;
}
- (void)setFont:(UIFont *)font
{
_font = font;
_textView.font = font;
}
#pragma mark - 事件
- (void)pinglun
{
NSLog(@"發送");
}
- (void)textViewDidChange:(UITextView *)textView
{
if (!_showLimitNum) return;
NSString *toBeString = textView.text;
UITextInputMode *current = [[UITextInputMode activeInputModes] firstObject];
if ([current.primaryLanguage isEqualToString:@"zh-Hans"]) {
// 中文輸入時,候選字會處於高亮狀態,此時不該急著截斷
UITextRange *selectedRange = [textView markedTextRange];
UITextPosition *position = [textView positionFromPosition:selectedRange.start
offset:0];
if (!position) {
if (toBeString.length > _limitNum) {
textView.text = [toBeString substringToIndex:_limitNum];
}
}
} else {
if (toBeString.length > _limitNum) {
textView.text = [toBeString substringToIndex:_limitNum];
}
}
}
#pragma mark - 鍵盤通知
- (void)keyboardWillShow:(NSNotification *)notification
{
NSDictionary *userInfo = [notification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
self.frame = CGRectMake(0,
CGRectGetHeight([UIScreen mainScreen].bounds)
- keyboardRect.size.height - 50,
CGRectGetWidth(_bottomView.frame),
CGRectGetHeight(_bottomView.frame));
}
- (void)keyboardWillHide:(NSNotification *)notification
{
self.frame = _rect;
}
@end
元件在 init 時就把自己擺在螢幕下方,並記錄初始 frame,鍵盤收起時直接還原。鍵盤彈起時則依通知中帶的鍵盤高度重新計算位置,讓輸入列緊貼鍵盤頂端。
字數限制最容易出問題的地方是中文輸入法:候選字尚未上屏時,markedTextRange 會有值,此時若急著截斷,使用者會打不完整的字。因此判斷方式是——只有在沒有高亮候選字時,才做長度統計與截斷。