加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:51:15 所属栏目:百科 来源:网络整理
导读:我正在以编程方式构建UIViews。如何在Swift中获取具有动作功能的UIButton? 以下代码不会得到任何操作: let btn: UIButton = UIButton(frame: CGRectMake(100,400,100,50))btn.backgroundColor = UIColor.greenColor()btn.setTitle("Click Me",forState: UI
我正在以编程方式构建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
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读