无法在NSMutableAttributedString中设置自定义字体

时间:2015-08-10 05:39:00

标签: ios objective-c iphone ipad nsmutableattributedstring

我无法在NSMutableAttributedString

中设置自定义字体

但是当将字体设置为System时,它工作正常。 这是我的代码:

 NSString *str=@"my attributed text";
    NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:str];
    UIFont *customFont =[UIFont fontWithName:@"Play-Regular" size:13.0];
    [attString addAttributes:@{
                               NSForegroundColorAttributeName: [UIColor colorWithRed:111.0/255.0 green:75.0/255.0 blue:26.0/255.0 alpha:1.0],
                               NSFontAttributeName: customFont,
                               } range:NSMakeRange(0,str.length)];

我无法在UISearchbar中设置自定义字体。

[[UITextField appearanceWhenContainedIn: [UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont fontWithName:@"Play-Regular" size:13.0]}];

虽然我已成功添加Play字体。

但是在设置

时它工作正常
[[UITextField appearanceWhenContainedIn: [UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:13.0]}];

1 个答案:

答案 0 :(得分:0)

试试这个

    NSMutableAttributedString *attributedstring = [[NSMutableAttributedString alloc] initWithString:@"My text"];
    [attributedstring addAttribute:NSForegroundColorAttributeName value:[UIColor myColor] range:NSMakeRange(0, self.selectedbanner.bannerTitle.length)];
    [attributedstring addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"myFont" size:fontsize] range:NSMakeRange(0, self.selectedbanner.bannerTitle.length)];
    myTextField.attributedText = attributedstring;

交叉检查您的字体名称,并确保已将该字体添加到项目包