var label = UILabel(frame: CGRectMake(0, 20, 200, 20)) label.textAlignment = NSTextAlignment.Center label.backgroundColor = UIColor.orangeColor() label.text = "lable" self.view.addSubview(label) let btn = UIButton(frame : CGRectMake(x, y , widthButton, heigthButton)) btn.setTitle((dicts["title"]), forState: .Normal) btn.backgroundColor = UIColor.blueColor() btn.addTarget(self, action: "press:" , forControlEvents: UIControlEvents.TouchUpInside) btn.tag = tag self.view.addSubview(btn) func press (sender: AnyObject) { if flag == true { sender.setTitle("player1", forState: .Normal) flag = false } else { sender.setTitle("player2", forState: .Normal) flag = true } } 

How to implement function that changed lable but not button? If you write lable.text then it is not available in the function, the declaration in the viewDidLoad method, where did I go wrong?

  • You need to have a label reference in its class, and use self.label instead of sender (sender is the reference to the button that calls your press function) - Max Mikheyenko
  • so it is necessary to change by pressing the button, can you give an example? - Yurjke

1 answer 1

Something like this

 class ViewController: UIViewController { var label:UILabel! var btn:UIButton! override func viewDidLoad() { label = UILabel(frame: CGRectMake(0, 20, 200, 20)) label.textAlignment = NSTextAlignment.Center label.backgroundColor = UIColor.orangeColor() label.text = "lable" self.view.addSubview(label) let btn = UIButton(frame : CGRectMake(0, 100 , 100, 44)) btn.setTitle("title", forState: .Normal) btn.backgroundColor = UIColor.blueColor() btn.addTarget(self, action: "press:" , forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(btn) } func press (sender: AnyObject) { label.text = "text"; } } 
  • nal while unwrapping an optional value - Yurjke
  • in the function, I replaced lable.setTitle with lable.text = - Yurjke
  • did not notice when he was changing - Max Mikheyenko
  • corrected the answer. - Max Mikheyenko
  • so if done. it works. strange somehow. My cycle is a bunch of buttons, whose names are taken from an array consisting of Dixenry. I debugged the debager, the plug-in on lable.text function somehow incorrectly sees it (although, if you make changes to the buttons - it works), maybe a bug) did the same through the storyboard, too, everything is ok. thank! - Yurjke