gpt4 book ai didi

swift - 创建 Swift 闭包以创建 UIView

转载 作者:行者123 更新时间:2023-12-01 13:13:18 26 4
gpt4 key购买 nike

我想将 DRY 应用于我在 swift 中创建的线条。我如何重构此代码以便调用闭包?它驻留在 View Controller 上。

var topLineView: UIView = {
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}()

var bottomLineView: UIView = {
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}()

var centerLineView: UIView = {
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}()

我尝试创建一个变量但是导致了一个错误:

let lineView = {
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}

var centerLineView = lineView()

错误(无法推断闭包类型等...)

最佳答案

Swift 无法推断闭包的返回类型,因此您需要提前告诉它您正在返回一个 UIView。这编译并运行良好。

let lineView = { () -> UIView in
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}
var myViewFromClosure = lineView()
var myViewFromClosure2 = lineView()
var myViewFromClosure3 = lineView()

不过,在这种情况下,我个人会选择 function 而不是 closure。像这样:

func lineViewFunc() -> UIView {
let lineView = UIView()
lineView.layer.borderWidth = 1.0
lineView.layer.borderColor = UIColor.lightGray.cgColor
return lineView
}

var myViewFromFunc = lineViewFunc()
var myViewFromFunc2 = lineViewFunc()
var myViewFromFunc3 = lineViewFunc()

关于swift - 创建 Swift 闭包以创建 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58509207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com