整理了一份Demo,因为每个项目具体的需求不一样,我只把基本的功能整理出来了
Demo放在GitHub上
项目中要实现填空题的作答功能,比如诗词填空:床前明月光,___________。举头望明月,________。要求只能编辑横线部分。
首先想到的是强大的YYKit,先在网上找了找,发现有一种方案是用label 加textfield的这种富文本编辑的方式实现的,虽然大体符合需求,但是排版会比较难看。
最后决定用YYTextView去实现,原理就是根据正则匹配题干和下划线,整个题目会被填空部分分割成几块,把各个分块binding,然后控制光标位置,只让光标落在下划线上。
创建题目:
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"#(填空题)枯藤老树昏鸦,# #,古道西风瘦马。# #,断肠人在天涯。# "];
text.yy_font = [UIFont systemFontOfSize:17];
text.yy_lineSpacing = 5;
text.yy_color = [UIColor blackColor];
YYTextView *textView = [YYTextView new];
textView.textParser = [YYTextEditBindingParser new];
textView.attributedText = text;
textView.frame = CGRectMake(5, 100, CGRectGetWidth(self.view.frame)-10, 200);
textView.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10);
textView.delegate = self;
if (kiOS7Later) {
textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
}
textView.scrollIndicatorInsets = textView.contentInset;
[self.view addSubview:textView];
self.textView = textView;
在代理方法里面控制光标位置
#pragma mark YYTextViewDelegate
- (BOOL)textViewShouldBeginEditing:(YYTextView *)textView{
if (textView.selectedRange.location==0 || textView.selectedRange.location >= textView.text.length) {
return NO;
}else{
return [self controllCursorRangeForTextView:textView];
}</