user8105388
user8105388

Reputation:

How to declare a programmed button as a var

I would to do a programmed button without the storyboard. The problem is that I can not call the button in a separate function like I can when I drag and drop a UIButton from a storyboard into a view controller. I do not want to use the storyboard at all.

//Trying to Create a var for btn

override func viewDidLoad() {
    super.viewDidLoad()

    let btn = UIButton(type: .custom) as UIButton
    btn.backgroundColor = .blue
    btn.setTitle("Button", for: .normal)
    btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
    btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
    self.view.addSubview(btn)
}

@objc func clickMe(sender:UIButton!) {
    print("Button Clicked")
}

func place() {
    //do something to btn.
}

Upvotes: 0

Views: 66

Answers (1)

carbonr
carbonr

Reputation: 6067

Read about variable scopes. In the question you have declared your button inside the method/function which restricts the scope of its usage within the method. When you declare the variable within the scope of the class/struct you can use it within other methods/functions.

let btn = UIButton(type: .custom)

override func viewDidLoad() {
    super.viewDidLoad()

    btn.backgroundColor = .blue
    // .. other settings here
    self.view.addSubview(btn)
}

@objc 
func clickMe(sender:UIButton) {
    print("Button Clicked")
}

func place() {
    btn.backgroundColor = .red
}

Upvotes: 1

Related Questions