swift – 如何以编程方式创建UIButton

我正在以编程方式构建UIViews。如何在Swift中获取具有动作功能的UIButton?

以下代码不会得到任何操作:

let btn: UIButton = UIButton(frame: CGRectMake(100,400,100,50))
btn.backgroundColor = UIColor.greenColor()
btn.setTitle("Click Me",forState: UIControlState.normal)
btn.addTarget(self,action: "buttonAction:",forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(buttonPuzzle)

以下选择器功能是:

func buttonAction(sender: UIButton!) {
    var btnsendtag: UIButton = sender
}
你只是错过了这个UIButton。为了补偿这一点,请更改其标签属性
这是你回答:
let btn: UIButton = UIButton(frame: CGRectMake(100,forControlEvents: UIControlEvents.TouchUpInside)
btn.tag = 1               // change tag property
self.view.addSubview(btn) // add to view as subview

Swift 3.0

let btn: UIButton = UIButton(frame: CGRect(x: 100,y: 400,width: 100,height: 50))
btn.backgroundColor = UIColor.green
btn.setTitle(title: "Click Me",for: .normal)
btn.addTarget(self,action: #selector(buttonAction),forControlEvents: .touchUpInside)
btn.tag = 1               
self.view.addSubview(btn)

这是一个示例选择器函数

func buttonAction(sender: UIButton!) {
    var btnsendtag: UIButton = sender
    if btnsendtag.tag == 1 {            
        //do anything here
    }
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...