将文本设置为不带选择的下划线

Den*_*Vog 5 underline nsattributedstring ios ios6

我试图让用户能够设置他们将键入下划线的文本,而不会选择当前的文本.这适用于iOS 6应用程序,在UITextView中输入文本.它将保存为NSAttributedString.大胆和斜体很好.关于下划线的一些事情是让它无法工作.

UITextView *textView = [self noteTextView];
NSMutableDictionary *typingAttributes = [[textView typingAttributes] mutableCopy];
[typingAttributes setObject:[NSNumber numberWithInt:NSUnderlineStyleSingle] forKey:NSUnderlineStyleAttributeName];
NSLog(@"attributes after: %@", typingAttributes);
[textView setTypingAttributes:typingAttributes];
NSLog(@"text view attributes after: %@", [textView typingAttributes]);
Run Code Online (Sandbox Code Playgroud)

我的初始日志语句表明它设置为下划线:

attributes after: {
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0xa9c5e30> font-family: \"Verdana\"; font-weight: normal; font-style: normal; font-size: 17px";
    NSKern = 0;
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
    NSUnderline = 1;
}
Run Code Online (Sandbox Code Playgroud)

但紧接着的日志语句不显示nsunderline属性.删除textView setTypingAttributes行没有任何影响.

text view attributes after: {
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0xa9c5e30> font-family: \"Verdana\"; font-weight: normal; font-style: normal; font-size: 17px";
    NSKern = 0;
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}
Run Code Online (Sandbox Code Playgroud)

我很难过为什么我的工作是粗体和斜体,但没有强调.也为什么它似乎最初获得属性,然后忘记它.请分享您的任何见解.谢谢.

mat*_*att 4

我认为您已经发现了一个错误,或者至少发现了一些未记录的行为。如果我将输入属性设置为红色,我可以这样做:

\n\n
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range\n        replacementString:(NSString *)string {\n    NSDictionary* d = textField.typingAttributes;\n    NSLog(@"%@", d);\n    NSMutableDictionary* md = [NSMutableDictionary dictionaryWithDictionary:d];\n    // md[NSUnderlineStyleAttributeName] = @(NSUnderlineStyleSingle);\n    md[NSForegroundColorAttributeName] = [UIColor redColor];\n    textField.typingAttributes = md;\n    return YES;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

使用该代码,用户的所有新输入都会显示为红色。但是,如果我取消注释行的注释,尝试在键入属性中添加下划线,则会破坏整个事情 - 我没有得到下划线,也没有得到红色!

\n\n

不过,您问题的其他部分的答案记录在案。您必须按照我的方式进行操作,在用户键入时重新断言键入属性,因为正如文档明确指出的那样,“当文本字段\xe2\x80\x99s 选择更改时,字典的内容会自动清除”(这就是您所问的“忘记”)。

\n