首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UIFont字体与描述符:大小:不保留自定义属性

UIFont字体与描述符:大小:不保留自定义属性
EN

Stack Overflow用户
提问于 2013-10-11 21:51:23
回答 2查看 1.2K关注 0票数 0

我正在使用iOS 7新的字体API。

我正在尝试将自定义属性添加到字体属性中。我可以用这个新属性生成一个UIFontDescriptor,但是当我用它创建一个新字体时,自定义属性就丢失了。

下面是我使用的UIFont类别方法:

代码语言:javascript
复制
- (UIFont*)fontWithCustomAttribute:(id)myNewAttribute
{
    UIFontDescriptor *newFontDescriptor = 
        [self.fontDescriptor fontDescriptorByAddingAttributes:
              [NSDictionary dictionaryWithObject:myNewAttribute
                                          forKey:@"NewAttribute"]];

    return [UIFont fontWithDescriptor:newFontDescriptor size:0];
}

newFontDescriptor包含myNewAttribute,但不包含返回字体的描述符。

有没有一种方法可以在UIFontDescriptor中自定义属性,并在创建字体时保留它们?

EN

回答 2

Stack Overflow用户

发布于 2013-10-11 22:16:36

是的,这是可能的,你可以编写你自己的category类,在里面传递你的字符串,并在你的category类中编写逻辑。因此,无论何时向category类的方法发送字符串,它都会扩展功能,并在此基础上获得所需的输出。例如,下面是在category类中编写的代码。只需在您的contoller类中导入category类,并调用以下方法并传递您的字符串:-

代码语言:javascript
复制
-(NSString*)getFontString:(NSString*)font
    NSString *str=font;
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:str];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,string.length)];
    [text setEnabled:YES];
    [text setAttributedText:string];
票数 0
EN

Stack Overflow用户

发布于 2013-10-11 22:24:43

您的自定义属性(在fontWithDescriptor:size:中)可能没有与之匹配的字体,所以它们会丢失,因为返回的字体没有这些属性。

当您替换以下代码时,此代码工作正常:

代码语言:javascript
复制
[NSDictionary dictionaryWithObject:myNewAttribute
                                      forKey:@"NewAttribute"]];

例如:

代码语言:javascript
复制
@{UIFontDescriptorFamilyAttribute : @"Georgia"}

所以问题肯定出在你的自定义属性上。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19319889

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档