iOS - 从UITextView获取字符串并将其转换为

时间:2017-01-28 14:47:41

标签: ios objective-c xcode

   - (void)textViewDidChangeSelection:(UITextView *)textView
{
        NSRange range = [bodyField selectedRange];
        NSString *str = [bodyField.text substringWithRange:range];

}

此时,我会在选择时实现类型的更改,从正常情况开始,但我无法继续。

编辑:感谢@danh:

唯一不起作用的是,如果我选择文本已经是粗体,则不会恢复正常。我该如何解决?

谢谢你们:)

1 个答案:

答案 0 :(得分:0)

在selectionChanged委托方法中更改文本视图的文本是错误的,因为对于选择中的中间步骤会重复调用该方法,并且在修改文本后再次调用该方法。

在选择保持不变的情况下,可以轻松修改所选范围内的文本属性。例如,如果要添加按钮或其他事件来触发更改...

// assuming you have an outlet to the text view called textView.
// assuming you have a button set to trigger this action.
- (IBAction)doit:(id)sender {

    // this way, the old attributed state will be removed and replaced
    // NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.textView.text];

    // this way, we'll add attributes to the existing attributes
    NSMutableAttributedString *attributedString = [self.textView.attributedText mutableCopy];

    UIFont *font = [UIFont boldSystemFontOfSize:17];
    NSRange selectedRange = [self.textView selectedRange];

    [attributedString setAttributes:@{ NSFontAttributeName: font } range:selectedRange];
    [self.textView setAttributedText:attributedString];
}