首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift中重命名属性的回退

Swift中重命名属性的回退
EN

Stack Overflow用户
提问于 2017-10-03 08:32:11
回答 1查看 171关注 0票数 0

我很难找到像这样的东西的备用方案

代码语言:javascript
复制
UIFontDescriptor.AttributeName
NSAttributedStringKey.foregroundColor

这个问题出现在XCode 9中的Swift 4中。

代码语言:javascript
复制
#if swift(>=4.0)
    if #available(iOS 11, *) {
        [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]
    } else {
        ["NSColor": UIColor.white]
    }
 #else 
       [NSForegroundColorAttributeName.rawValue: UIColor.white]

但是,对于UIFontDescriptor,我找不到任何可以在iOS 8上工作的东西。另外,如果你能改进这个破解,那就太棒了。

EN

回答 1

Stack Overflow用户

发布于 2017-10-03 12:28:16

在Swift 4中,您使用UIFontDescriptor.AttributeName.xxxNSAttributedStringKey.yyy wherexxxandyyy`是所需的名称。

在Swift 3中,您使用UIFontDescriptorXXXAttributeNSYYYAttributeName,其中XXXYYY是所需的名称。

只要您使用的密钥在iOS 8中存在,Swift 4代码就可以在iOS 11、10、9和8上正常工作。您不需要#if#available

这意味着以下代码可以在Xcode9中用于部署目标为iOS 8或更高版本的应用程序:

代码语言:javascript
复制
let fontDesc = UIFontDescriptor()
fontDesc.addingAttributes([ .name: "Helvetica" ])
let font = UIFont(descriptor: fontDesc, size: 14)
let dict = [ NSAttributedStringKey.foregroundColor: UIColor.green, NSAttributedStringKey.font: font ]
let attrStr = NSAttributedString(string: "Hello", attributes: dict)

如果您需要同时使用Xcode 9和Xcode 8 (Swift 4和Swift 3)构建此代码,则需要执行以下操作:

代码语言:javascript
复制
let fontDesc = UIFontDescriptor()
#if swift(>=4.0)
    fontDesc.addingAttributes([ .name: "Helvetica" ])
#else
    fontDesc.addingAttributes([ UIFontDescriptorNameAttribute: "Helvetica" ])
#endif
let font = UIFont(descriptor: fontDesc, size: 14)
#if swift(>=4.0)
    var dict = [ NSAttributedStringKey.foregroundColor: UIColor.yellow, NSAttributedStringKey.font: font ]
#else
    var dict = [ NSForegroundColorAttributeName: UIColor.yellow, NSFontAttributeName: font ]
#endif

let attrStr = NSAttributedString(string: "Hello", attributes: dict)

请注意,在这两组代码中,您都没有对任何键使用rawValue。而且你应该注意到对密钥串进行硬编码。使用提供的常量。

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

https://stackoverflow.com/questions/46535574

复制
相关文章

相似问题

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