如何以编程方式识别ViewController子视图中按钮的单击动作?

时间:2019-01-22 08:47:50

标签: swift xcode

我在subView中有一个视图mainViewControllersubView有4个按钮。如何识别mainViewController中这些按钮的onClick动作?

下面是我的mainViewController

import UIKit

class HomeViewController: UIViewController{

 let tableList = ["HIPAA Rules", "Know Your HIPPA Status", "Covered Entity", "Business Associate"]
var metrics : [String : CGFloat] = [:]

let menuBar = MenuBar()
let table = OptionsTable()
var views : [UIView] = []
override func viewDidLoad() {

    super.viewDidLoad()

    navigationController?.navigationBar.barTintColor = UIColor.getColorFromHex(hexCode: "1B9AF7")
    navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]

    setUpTable()
}


private func setUpTable(){
    views += [table]
    view.addSubview(table)
    table.backgroundColor = UIColor.red
    //Code For Constraints Of the SubView
    table.setUpButtons(numberOfButtons: 4, buttonTitleList: tableList, optionsTableHeight: optionTableHeight)


}

下面是我的OptionsTable //主ViewController的子视图

class OptionsTable: UIView {


override init(frame: CGRect) {
    super.init(frame: frame)
}

func setUpButtons(numberOfButtons : Int, buttonTitleList : [String], optionsTableHeight : CGFloat) {

    let cellHeight = optionsTableHeight / CGFloat(numberOfButtons)

    for buttonNumber in 0...numberOfButtons-1{
        var views : [UIView] = []
        var metrics : [String : CGFloat] = [:]
        let paddingInTermsOfButtons = (numberOfButtons-buttonNumber)-1

        let button = UIButton()

        button.setTitle(buttonTitleList[buttonNumber], for: .normal)
        button.backgroundColor = UIColor.white
        button.layer.borderColor = UIColor.gray.cgColor
        button.layer.borderWidth = 1;
        button.setTitleColor(UIColor.black, for: .normal)


        print("For button : \(buttonNumber)" )
        print(self.frame)
        self.addSubview(button)

        views += [button]

        //Code For Constraints of the buttons

    }
}

那么,我如何识别OptionsTable中这些按钮的onclick动作,因为它们是动态创建的?

1 个答案:

答案 0 :(得分:0)

您必须添加目标以识别按钮中的点击事件。

  

快速

buttonOne.tag = index
buttonOne.addTarget(self, action: #selector(buttonOneClicked), for: .touchUpInside)

点击按钮时将调用此方法。

@objc func buttonOneClicked(button: UIButton)  {
        //Do whatever you want to do here and check button tags so you will get to know which index is clicked
    }
  

Objecitve-C

buttonOne.tag = index;
[buttonOne addTarget:self action:@selector(buttonOneClicked:) forControlEvents:UIControlEventTouchUpInside];

点击按钮时将调用此方法。

- (void) buttonOneClicked:(UIButton *) sender {
    //Do whatever you want to do here and check button tags so you will get to know which index is clicked
}