2017-06-24 18 views
0

我有三个按钮可以更改背景的颜色。我想在按下时隐藏红色按钮。如果按下GREEN或BLUE按钮,则显示它。 GREEN和BLUE按钮也是如此。按下时隐藏UIButton,然后在另一个按钮被按下时显示它

我找不到方法叫removeFromSuperview。在ObjectiveC中,我曾使用mybutton.hidden = true 但这不起作用。

ViewController: UIViewController { 
    @IBAction func RED(_ sender: Any) { 

    print("background was \(String(describing: self.view.backgroundColor))") 
    self.view.backgroundColor = UIColor.red 
    print("background is now \(String(describing: self.view.backgroundColor))") 
} 

@IBAction func GREEN(_ sender: Any) { 
    print("background was \(String(describing: self.view.backgroundColor))") 
    self.view.backgroundColor = UIColor.green 
    print("background is now \(String(describing: self.view.backgroundColor))") 
} 

@IBAction func BLUE(_ sender: UIButton) { 
    print("background was \(String(describing: self.view.backgroundColor))") 
    self.view.backgroundColor = UIColor.blue 
    print("background is now \(String(describing: self.view.backgroundColor))") 
} 
+1

你应该可以做'button.isHidden = true'?如果它在ObjC中工作,它也应该在Swift中工作(通过翻译)。 – Peterdk

+0

hmm。也许我做错了什么!我会再尝试。 – Splenso

+0

nope我再次尝试,得到UIButton没有成员“ishidden” – Splenso

回答

0

您需要为每个按钮创建一个IBOutlet才能访问“isHidden”属性。现在你只有一个IBAction被定义(至少在你提供的代码中)。要创建IBOutlet,请将按钮从按钮拖动到视图控制器的代码,与您创建IBActions的操作类似。在弹出窗口中,确保“Connection”表示“Outlet”和“Type”是“UIButton”。根据需要命名它们(例如,redButton,blueButton)。然后你可以在适当的位置输入“redButton.isHidden = true”。

IBAction只允许您控制按钮按下时按钮的功能。 IBOutlet需要访问UIButton的属性。

+0

哇!有用!感谢你写得很好的答案;) – Splenso

相关问题