NSAttributedString赢得改变字体

时间:2014-08-24 07:15:00

标签: ios objective-c nsattributedstring

我正在尝试使用UITextField格式化NSAttributedString的占位符文字。此代码可成功用于前景色和字距调整属性。但是,它不会更改字体或字体大小。我究竟做错了什么?谢谢!

NSAttributedString *aString = [[NSAttributedString alloc] initWithString:
                                  @"USER NAME"
                                  attributes:@{
                                              NSForegroundColorAttributeName: [UIColor redColor],
                                              NSFontAttributeName : [UIFont fontWithName:@"Georgia" size:8.0f],
                                              NSKernAttributeName : [NSNumber numberWithFloat:3.0f]
                                                                                                    }];
self.userNameTextField.attributedPlaceholder = [aString copy];

2 个答案:

答案 0 :(得分:0)

看似占位符字体大小由UITextField的字体控制,所以我认为你必须继承UITextField并添加:

-(void)drawPlaceholderInRect:(CGRect)rect
{
    NSString *aString = @"USER NAME";
    [aString drawInRect:rect withAttributes:@{NSForegroundColorAttributeName: [UIColor redColor], NSFontAttributeName : [UIFont fontWithName:@"Georgia" size:8.0f], NSKernAttributeName : [NSNumber numberWithFloat:3.0f]}];
}

答案 1 :(得分:0)

对我来说,当我为UITextField设置自定义字体,然后为占位符设置其他属性时,它可以正常工作。我的例子有效:

_searchField.font = [UIFont fontWithName:fontRokkitRegular size:20];
UIColor *color = [UIColor colorWithRed:150.0f/255 green:150.0f/255 blue:150.0f/255 alpha:1];
_searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Keyword search" attributes:@{NSForegroundColorAttributeName:color}];