2017-04-01 31 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首先提供一個完整的,正確的答案。你的回答是什麼? –