如何以编程方式在按钮操作中调用/访问标签?

时间:2017-04-01 10:09:12

标签: ios swift swift3

//This is the label

let changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))

self.view.addSubview(changeLbl)

//This is the button

let submitButton = UIButton(type: .system) // let preferred over var here

submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)

self.view.addSubview(submitButton)

//and this is action of above button

func buttonAction(sender: UIButton!) {

}

我想在以下按钮功能中调用上面的标签?像

func buttonAction(sender: UIButton!) {
    changeLbl.ishidden = true 

//想在这里访问标签,但它没有以这种方式工作。     }

3 个答案:

答案 0 :(得分:1)

如果你想访问changeLbl,你需要像这样定义实例变量,并在类中提供全局范围。

class ViewController: UIViewController {

    var changeLbl : UILabel!
    var submitButton : UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

         //This is the UILabel
        changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))

        self.view.addSubview(changeLbl)

         //This is the button
        submitButton = UIButton(type: .system) // let preferred over var here

        submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)
        self.view.addSubview(submitButton)

    }

    //and this is action of above button

    func buttonAction(sender: UIButton!) {
        changeLbl.isHidden = true
    }
}

答案 1 :(得分:0)

changeLbl是一个局部变量。它仅在创建标签的方法范围内可见。

如果您不想使用实例变量 - 这是正常方式 - 并且只有一个UILabel,您可以从subviews数组中获取标签

func buttonAction(sender: UIButton) {
    if let changeLbl = self.view.subviews.filter({ $0 is UILabel}).first {
       changeLbl.ishidden = true
    }
}

答案 2 :(得分:0)

如果您想要访问标签,则在全球范围内声明它。 以下代码:

class LabelDemo: UIViewController{
     var changeLbl: UILabel!
     override func viewDidLoad() {
         super.viewDidLoad()

         changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))
         changeLbl.backgroundColor = UIColor.black
         self.view.addSubview(changeLbl)

         //This is the button

         let submitButton = UIButton(type: .system) // let preferred over var here
        submitButton.backgroundColor = UIColor.green
        submitButton.frame = CGRect(x: 50, y: 150, width: 50, height: 30)
        submitButton.setTitle("hide", for: .normal)
        submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)

        self.view.addSubview(submitButton)


     }
    func buttonAction(sender: UIButton!) {
        if changeLbl.isHidden {
            changeLbl.isHidden = false
        }else{
            changeLbl.isHidden = true
        }

     }
}