platform :ios, '9.0'
target '项目名' do
pod 'YYText'
end
#import "YYTextView.h" //引入头文件
//文字输入内容 设置属性
@property (nonatomic, strong) YYTextView *contentTextView;
/** 内容视图 */ //懒加载
- (YYTextView *)contentTextView{
if (_contentTextView == nil) {
_contentTextView = [[YYTextView alloc]init];
// _contentTextView.extraAccessoryViewHeight = 100; //键盘弹出时这个 会 自动 便宜的 一个 属性
_contentTextView.placeholderText = @"宝贝满足你的期待值么?说说你的使用心得,分享给想买的他 们吧";
_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];
//添加字数统计观察者
[self addObserver];
#pragma mark 关键方法 YYTextView 字数监听 添加通知
-(void)addObserver{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChangeNotification:) name:YYTextViewTextDidChangeNotification object:self.contentTextView];
}
//移除通知
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
//字数限制 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)];
}
}