let loginRegisterButton:UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .white
button.setTitle("Register", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(.white, for: .normal)
return button
}()
Run Code Online (Sandbox Code Playgroud)
是这个变量还是函数,它为什么会返回值?我们为什么称呼它?它不起作用parenthesis,为什么?
das*_*ght 13
这是一个在同一地点创建和使用的闭包.当您无法将所有内容放在单个表达式中时,可以将其用于初始化.创建只读(let相对于var)字段时,此功能很有用.
在上面的例子中,代码创建一个按钮,然后在返回结果之前对其执行其他配置.这是将代码移动init到初始化位置附近的代码块的好方法.
可视化正在发生的事情的一种方法是考虑执行相同操作的命名函数:
func makeWhiteButton() -> UIButton {
let button = UIButton(type: .system)
button.backgroundColor = UIColor.White
button.setTitle("Register", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(.white, for: .normal)
return button
}
Run Code Online (Sandbox Code Playgroud)
现在您可以在初始化程序中使用它
let loginRegisterButton:UIButton = makeWhiteButton()
Run Code Online (Sandbox Code Playgroud)
您帖子中的代码使用匿名"闭包"功能执行相同的操作.闭包之后的括号与makeWhiteButton上面的括号相同.
| 归档时间: |
|
| 查看次数: |
671 次 |
| 最近记录: |