我正在创建一个应用程序,我必须在其中实现如下功能:
1)写入textview
2)从文本视图中选择文本
3) 允许用户对所选文本应用粗体、斜体和下划线功能。
我已经开始使用 NSMutableAttributedString 来实现它。它适用于粗体和斜体,但仅用选定的文本替换文本视图文本。
-(void) textViewDidChangeSelection:(UITextView *)textView
{
rangeTxt = textView.selectedRange;
selectedTxt = [textView textInRange:textView.selectedTextRange];
NSLog(@"selectedText: %@", selectedTxt);
}
-(IBAction)btnBold:(id)sender
{
UIFont *boldFont = [UIFont boldSystemFontOfSize:self.txtNote.font.pointSize];
NSDictionary *boldAttr = [NSDictionary dictionaryWithObject:boldFont forKey:NSFontAttributeName];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:selectedTxt attributes:boldAttr];
txtNote.attributedText = attributedText;
}
有人可以帮我实现这个功能吗?
提前致谢。
你不应该使用didChangeSelection
以此目的。使用shouldChangeTextInRange
反而。
这是因为当您将属性字符串设置为新字符串时,您不会替换特定位置的文本。您可以用新文本替换全文。您需要范围来定位要更改文本的位置。
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
NSMutableAttributedString *textViewText = [[NSMutableAttributedString alloc]initWithAttributedString:textView.attributedText];
NSRange selectedTextRange = [textView selectedRange];
NSString *selectedString = [textView textInRange:textView.selectedTextRange];
//lets say you always want to make selected text bold
UIFont *boldFont = [UIFont boldSystemFontOfSize:self.txtNote.font.pointSize];
NSDictionary *boldAttr = [NSDictionary dictionaryWithObject:boldFont forKey:NSFontAttributeName];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:selectedString attributes:boldAttr];
// txtNote.attributedText = attributedText; //don't do this
[textViewText replaceCharactersInRange:range withAttributedString:attributedText]; // do this
textView.attributedText = textViewText;
return false;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)