ios - 如何在 Textview 中点击时更改文本的颜色

标签 ios objective-c colors uitextview nsrange

我需要在 UITextView 中点击更改文本颜色。我在 TextView 的选定文本上得到了 NSRange,但无法使用此代码更改其颜色。

[mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:10.0/255.0 green:15.0/255.0 blue:5.0/255.0 alpha:1.0] range:range1];

有什么方法可以改变 TextView 中的点击颜色变化吗?

最佳答案

我希望,这段代码可以帮到你 :) 在我的场景中,我通过点击 uiButton 更改选定的 textColor,您可以尝试这种方式。

// When text is tapped or selected by user we can change the

- (IBAction)applyBlueColor:(id)sender {

    // getting textRange
    NSRange textRange = [_textView selectedRange];

    NSDictionary *attributeDictionary = [_textView.textStorage attributesAtIndex:textRange.location
                                                                    effectiveRange:nil];

    if ([attributeDictionary objectForKey:NSForegroundColorAttributeName] == nil ||
        [attributeDictionary objectForKey:NSForegroundColorAttributeName] != [UIColor blackColor]) {
        // Setting blue color to my selected text.
        NSDictionary *colorDictionary = @{NSForegroundColorAttributeName: [UIColor blueColor]};
        [_textView.textStorage beginEditing];
        [_textView.textStorage setAttributes:colorDictionary range:textRange];
        [_textView.textStorage endEditing];
    }

}

关于ios - 如何在 Textview 中点击时更改文本的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25287159/

相关文章:

iphone - 动态检查类是否通过 respondsToSelector : 响应选择器

ios - 如何使用 Cordova 项目将设置正确添加到 iOS 应用程序?

ios - 以编程方式创建 navigationController (Swift)

ios - UIPickerView 行在滚动期间消失

ios - 自定义 uitableviewcell 突出显示颜色

eclipse - 使用深色 Eclipse 颜色主题和比较编辑器

javascript - 将数组传递给 Flurry 的 setAge (Cordova)

javascript - react-native 中的 clonewithrows 数组问题

java - Android操作栏自定义颜色样式

java - 光线追踪三角形的问题(方向和着色)