如何将已编程的按钮声明为var

时间:2018-08-24 02:24:28

标签: ios swift uibutton

我会在没有情节提要的情况下执行一个已编程的按钮。问题是我无法像在将UIButton从情节提要板拖放到视图控制器中一样,无法在单独的函数中调用按钮。我根本不想使用情节提要。

//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.
}

1 个答案:

答案 0 :(得分:1)

阅读有关变量作用域的信息。在问题中,您已在方法/函数内部声明了按钮,这限制了该按钮在方法中的使用范围。在类/结构的范围内声明变量时,可以在其他方法/函数中使用它。

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
}