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


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

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

编辑:感谢@danh:

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

谢谢你们:)

在 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];
}

最新更新