platform :ios, '9.0'
target '項(xiàng)目名' do
pod 'YYText'
end
#import "YYTextView.h" //引入頭文件
//文字輸入內(nèi)容 設(shè)置屬性
@property (nonatomic, strong) YYTextView *contentTextView;
/** 內(nèi)容視圖 */ //懶加載
- (YYTextView *)contentTextView{
if (_contentTextView == nil) {
_contentTextView = [[YYTextView alloc]init];
// _contentTextView.extraAccessoryViewHeight = 100; //鍵盤彈出時(shí)這個(gè) 會(huì) 自動(dòng) 便宜的 一個(gè) 屬性
_contentTextView.placeholderText = @"寶貝滿足你的期待值么复颈?說(shuō)說(shuō)你的使用心得诉稍,分享給想買的他 們吧";
_contentTextView.placeholderFont = [UIFont pingFangSCWithWeight:PFFontWeightStyleRegular size:15];
_contentTextView.placeholderTextColor = HEX(0x999999);
_contentTextView.font = [UIFont pingFangSCWithWeight:PFFontWeightStyleRegular size:15];
_contentTextView.textColor = HEX(0x333333);
_contentTextView.delegate = self;
// [_contentTextView becomeFirstResponder];
}
return _contentTextView;
}
//
[self.view addSubview:self.contentTextView];
//添加字?jǐn)?shù)統(tǒng)計(jì)觀察者
[self addObserver];
#pragma mark 關(guān)鍵方法 YYTextView 字?jǐn)?shù)監(jiān)聽 添加通知
-(void)addObserver{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChangeNotification:) name:YYTextViewTextDidChangeNotification object:self.contentTextView];
}
//移除通知
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
//字?jǐn)?shù)限制 200 字
-(void)textViewDidChangeNotification:(NSNotification *)obj{
YYTextView *textView = (YYTextView *)obj.object;
NSString *string = textView.text;
NSInteger maxLength = 200;
//獲取高亮部分
YYTextRange *selectedRange = [textView valueForKey:@"_markedTextRange"];
NSRange range = [selectedRange asRange];
NSString *realString = [string substringWithRange:NSMakeRange(0, string.length - range.length)];
if (realString.length >= maxLength){
textView.text = [realString substringWithRange:NSMakeRange(0, maxLength)];
}
}