How do I create a basic UIButton programmatically?

后端 未结 30 1202
清歌不尽
清歌不尽 2020-11-22 14:41

How can I create a basic UIButton programmatically? For example in my view controller, when executing the viewDidLoad method, three UIButton<

30条回答
  •  余生分开走
    2020-11-22 15:26

    For Swift 2.2 (with the with the new "selector" declaration).

    let btn = UIButton(type: UIButtonType.System) as UIButton
    btn.frame = CGRectMake(0, 0, 100, 20) // set any frame you want
    btn.setTitle("MyAction", forState: UIControlState.Normal)
    btn.addTarget(self, action: #selector(MyClass.myAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(btn)
    
    
    func myAction(sender:UIButton!){
      // Some action 
    }
    

提交回复
热议问题