NSAttributedString的粗体部分,不知道长度

时间:2014-11-21 15:02:24

标签: ios objective-c nsstring uitextfield nsattributedstring

我正在研究应用程序,它将从UITextFields获取用户输入的数据,例如用户的名字和姓氏。稍后,我想以粗体显示此数据。

我已阅读NSAttributedString change style to bold without changing pointSize?Any way to bold part of a NSString?,但这些似乎表明您必须知道要设置为粗体的字符范围。

在我的情况下,在用户输入数据之前,我实际上并不知道字符串的长度......在发生这种情况之前,我怎么知道要设置为粗体的字符串长度是多少?

以下是我正在使用的UITextFields的属性,稍后我将以粗体显示。

@property (strong, nonatomic) IBOutlet UITextField *firstName;
@property (strong, nonatomic) IBOutlet UITextField *lastName;

以下是我目前正在创建字符串来存储文本字段中的信息的方式,所有这些都要以粗体显示:

NSString *firstName = [_firstName text];
NSString *lastName  = [_lastName text];

1 个答案:

答案 0 :(得分:0)

您可能不知道在编写代码时输入到文本框中的文本的长度,但是您将在运行时知道。

尝试这样的事情:

NSMutableAttributedString *attribFirstNameString = [[NSMutableAttributedString alloc] initWithString: [firstName text]];
NSRange firstNameRange = NSMakeRange(0, [[firstName text] length]);
[attribFirstNameString addAttribute: NSFontAttributeName value: [UIFont boldSystemFontOfSize: 20.0f] range: firstNameRange];
[firstName setAttributedText: attribFirstNameString];
相关问题