如何在 nib 创建的自定义视图中为按钮创建操作。
我创建了Outlet
,它已连接到自定义ViewController
,但当我尝试执行操作时,它无法正常工作。
答案 0 :(得分:2)
这是你可以做的
创建 VIEW (自定义视图)的插座。然后像这样将按钮添加到按钮
self.viewName.buttonName addTarget:self action:@selector(actionName) forControlEvents:UIControlEventTouchUpInside];
还有其他选项,例如将块传递给视图或使用委托模式,但是执行这样一个简单的任务将更具有过分功能。当您在XIB中处理单独的视图时,这将更简单,更好。
答案 1 :(得分:1)
如果您正在使用笔尖或故事板文件,那么您甚至不需要按钮的插座。只需从按钮拖动到您的班级,然后选择“操作”而不是“插座”。它甚至可以让您选择要接收的操作类型,例如“TouchUpInside”。如果您需要对按钮进行更改,在单击它之后,您也可以在新生成的方法中执行此操作,因为它具有sender属性,即您的按钮。
答案 2 :(得分:0)
yourView.yourButton.addTarget(self, action: #selector(yourFuncName(_:)), for: .touchUpInside)
然后在某处声明您的func,如下所示:
@objc func yourFuncName(_ sender: UIButton) {
do something here}
答案 3 :(得分:0)
//Button action using both addTarget and Closure
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: CustomImageView!
@IBOutlet weak var awesomeView: AwesomeView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
awesomeView.button1.addTarget(self, action: #selector(button1Action(_:)), for: .touchUpInside)
awesomeView.button2Pressed = {
print("Closure button pressed")
}
}
@objc func button1Action(_ sender: UIButton) {
// do something here
}
}
//UIView Declaration
@IBDesignable class AwesomeView: UIView {
let kCONTENT_XIB_NAME = "AwesomeView"
@IBOutlet var containerView: UIView!
@IBOutlet weak var button1 : UIButton!
@IBOutlet weak var button2 :UIButton!
//create your closure here
var button2Pressed : (() -> ()) = {}
override init(frame: CGRect) {
super.init(frame: frame)
initNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initNib()
}
func initNib() {
let bundle = Bundle(for: AwesomeView.self)
bundle.loadNibNamed(kCONTENT_XIB_NAME, owner: self, options: nil)
addSubview(containerView)
containerView.frame = bounds
containerView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
@IBInspectable var button1Title: String = "" {
didSet {
button1.setTitle(button1Title, for: .normal)
}
}
@IBAction func tapOnButtonPressed(_ sender: Any) {
}
@IBAction func tapOnButton2Pressed(_ sender: Any) {
button2Pressed()
}
}