2017-04-01 29 views
-1
//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 

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

+0

你面临的问题是什么? – shallowThought

+0

我不能让访问按钮功能标签... @shallowThought – Bilal

+0

到底会发生什么“我不能让访问标签”?编译错误?运行时错误?哪一个? – shallowThought

回答

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 
    } 
} 
0

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

如果你不想使用实例变量 - 这是正常的方式 - 只有一个UILabel可以从subviews阵列

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

这种方法很脆弱 - 不推荐使用。如果稍后将标签移动到另一个视图对象或UIStackView中,它会停止工作。同样,如果你以后决定从'UILabel'标签视图更改为'UITextField'。 –

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 
     } 

    } 
} 
+0

类的名称,如'labelDemo'应该以大写字母开头。 –

+0

jignesh Vadadoriya首先提供一个完整的,正确的答案。你的回答是什么? –