UITextView-设置属性



我有一个UITextView和一个带三个按钮的栏,它们可以切换粗体、斜体和下划线。我已经将TextView的文本设置为attribute,它的"允许编辑属性"选项设置为YES。尽管编辑所选文本的代码正在工作(这里有一个例子):

       UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Light" size:20];
    NSDictionary *dict = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];

    //edit selection
    NSRange selectedRange = _noteTextView.selectedRange;

    [[_noteTextView textStorage] beginEditing];
    [[_noteTextView textStorage] addAttribute:NSFontAttributeName value:font range:selectedRange];
    [[_noteTextView textStorage] addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:selectedRange];
    [[_noteTextView textStorage] endEditing];

    [[_noteTextView textStorage] setAttributes:dict range:selectedRange];

我在设置文本视图指示器的属性时遇到问题。[[_noteTextView textStorage] addAttribute:]不工作,或者我可能对范围有问题。有什么建议吗?提前感谢!

尝试使用此设置范围[textView rangeForUserParagraphAttributeChange];

它将设置整个段落的属性,而不仅仅是选定的范围。

编辑:如果插入符号位置之外有文本,您可能必须将范围扩展一个字符,以确保键入的后续字符将位于应用属性的范围内。

将属性应用于范围可以做到这一点,它将它们应用于范围,而不是应用于超出范围键入的任何文本。如果范围的长度为零(即未选择任何内容),那么我猜您的属性将不应用于任何内容。

最新更新