简化这段冗长的UIbutton代码可以通过使用Swift的闭包(closure)来实现。闭包是一种可以捕获和存储代码块的一种方式,类似于匿名函数或Lambda表达式。下面是简化代码的示例:
// 原始的冗长代码
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 100, width: 200, height: 50)
button.setTitle("Click me", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .blue
button.layer.cornerRadius = 10
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
// 使用闭包简化代码
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 100, width: 200, height: 50)
button.setTitle("Click me", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .blue
button.layer.cornerRadius = 10
button.addAction(UIAction(handler: { _ in
self.buttonTapped(button)
}), for: .touchUpInside)
在上面的代码中,我们使用addAction(_:for:)
方法将一个闭包作为按钮的动作处理器添加进去,代替了原始代码中的addTarget(_:action:for:)
方法。
需要注意的是,为了确保闭包中可以正确地访问到按钮实例以及对应的方法,我们使用了self.buttonTapped(button)
来传递按钮实例给按钮的响应方法buttonTapped(_:)
。
云+社区沙龙online第5期[架构演进]
“中小企业”在线学堂
云+社区技术沙龙[第9期]
云+社区技术沙龙[第14期]
腾讯技术创作特训营第二季第3期
云+社区沙龙online [新技术实践]
618音视频通信直播系列
实战低代码公开课直播专栏
“中小企业”在线学堂
云+社区技术沙龙[第5期]
实战低代码公开课直播专栏
领取专属 10元无门槛券
手把手带您无忧上云