ios - 如何使用 Button 制作自定义视图
问题描述
我想制作一个带有标签和按钮的自定义视图。
我将不得不在多个视图控制器中显示这个视图,但是点击按钮的动作是不同的,所有视图控制器都是如此。
我怎么解决这个问题。?
解决方案
创建一个带有标签和按钮的 UIView 子类。在该视图中添加一个可选的闭包属性。
class CustomView: UIView {
var buttonAction: (()->Void)?
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
//add label and button
let button = UIButton()
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
}
@objc func buttonTapped(_ sender: UIButton) {
if let buttonAction = self.buttonAction {
buttonAction()
}
}
}
并在任何视图控制器中添加此视图的实例。要在该特定视图控制器中获取按钮操作,请将闭包分配给可选的闭包属性。
class ViewController: UIViewController {
let customView = CustomView()
override func viewDidLoad() {
super.viewDidLoad()
// add customView in self.view or any other view
customView.buttonAction = { [weak self] in
print("button tapped")
//do your actions here
}
}
}
推荐阅读
- python-3.x - Random connection errors with aio_pika after 2 days of running
- datetime - 在兼容的 SQLServer 2014 vs SQLServer2016 中,mssql-jdbc datetime java 类型转换为 datetime2
- android - Android View 上的 Framwork7 Popover 问题
- javascript - How to load a table which sum the values (from database) when clicking the check box. in an onchange function in dropdown
- sql - Oracle 中有 ARRAY_AGG PostgreSQL 函数的类似物吗?
- javascript - 如何在 ubuntu 中使用 nodejs 连接 VPN
- apache - VHost 中的 RewriteRule 解释
- redis - 使用关联数组总值计数 Lua
- xpath - XPath 1.0 上的拆分方法
- mongodb - 删除在任何 mongodb 数组中找到的字段