如何以编程方式向Swift中的UIButton添加标记

如何以编程方式向Swift中的UIButton添加标记,swift,swift4,programmatically,Swift,Swift4,Programmatically,我知道如何在main.storyboard文件中添加标记,但现在我正在以编程方式创建所有内容。然而,我在网上找不到任何能告诉我如何在按钮上添加标签的东西。我试图阅读苹果的文档,但不知道如何实现它 例如,我是如何创建按钮的,如何向其添加标记,以便当我创建多个按钮并希望将它们链接到单个操作时,我可以知道按下了哪个按钮 let buttonOne() : UIButton { let button = UIButton(type: .system) button.backgroundCo

我知道如何在
main.storyboard
文件中添加标记,但现在我正在以编程方式创建所有内容。然而,我在网上找不到任何能告诉我如何在按钮上添加标签的东西。我试图阅读苹果的文档,但不知道如何实现它

例如,我是如何创建按钮的,如何向其添加标记,以便当我创建多个按钮并希望将它们链接到单个操作时,我可以知道按下了哪个按钮

let buttonOne() : UIButton { 
   let button = UIButton(type: .system)
   button.backgroundColor = .red
   return button
}()
试试这个:

let buttonOne() : UIButton { 
   let button = UIButton(type: .system)
   button.backgroundColor = .red
   button.tag = 2
   return button
}()
声明按钮

let menuChooseButton = UIButton()
menuChooseButton.frame.origin.y = 0
menuChooseButton.frame.origin.x = xPosition
menuChooseButton.frame.size.width = subViewWidth
menuChooseButton.frame.size.height = subViewHeight
menuChooseButton.backgroundColor = .clear
menuChooseButton.setTitle("", for: .normal)
menuChooseButton.tag = i
menuChooseButton.addTarget(self, action: #selector(menuSelectAction), for: .touchUpInside)
        menuScrollView.addSubview(menuChooseButton)
定义按钮动作

@objc func menuSelectAction(sender: UIButton!){
    var tagNo: Int = sender.tag
    if tagNo == 0{
        // Whatever you want
    }
}

继承自并且有一个属性他们继承了标记0,我想将其更改为例如2请看答案,它非常简单。明白了,你是对的,它非常简单。我觉得我做错了,所以我想我会问:)太好了,我试着这么做,但我认为这是不对的