ios - 在旧版 iOS 版本上快速传递属性

标签 ios swift

举个例子,我有以下代码,它接受一个字符串和一个 UITextContentType。

var items: [Item] = [
    TextField.init(
        title: "First Name", 
        textContentType: UITextContentType.givenName
    ),
]

但我的应用程序针对的是实现了 UITextContentType 的 iOS 10 之前的版本。处理这个问题的最佳方法是什么?

Xcode 修复它希望我 @available 到封闭的 var 或类。但这意味着在以前的版本中我的应用程序会崩溃。

这也是我设置 textContentType 的代码。

if #available(iOS 10.0, *) {
    textField.textContentType = textContentType
}

所以基本上我想说的是,如果它不在 iOS 上,则不要传递任何内容,或者 nil 或类似的内容。

如何才能实现这一目标,同时仍然以尽可能最简洁的方式编写不重复的代码?

最佳答案

我实际上只是通过将代码更改为以下内容来解决这个问题。

var items: [Item] = [
    TextField.init(title: "First Name", textContentType: {() in 
        if #available(iOS 10.0, *) { 
            return UITextContentType.givenName 
        } else { 
            return nil 
        } 
    }()),
]

如果其他人有关于如何使代码更简洁、更短的想法,那就太棒了。

关于ios - 在旧版 iOS 版本上快速传递属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46677982/

相关文章:

iphone - 来自应用程序委托(delegate)的 presentModalViewController

ios - NSObject does not have a member named Key 错误

ios - 在 Button Swift 中通过标签发送行和部分

ios - 如何在 Swift 中解释从 CMSampleBuffer 派生的像素数组

ios - AWS 认知错误 : Authentication delegate not set

swift - 无法为扩展方法 UIAlertController 提供参数值

iOS 9 - 重定向到通用链接不起作用

iOS:Apple 是否禁用了保存到主屏幕的 Web 应用程序的 HTML5 离线功能?

swift - fatal error : init(coder:) has not been implemented

ios - 按下主页按钮后 NSTimer 不触发