单击时使按钮显示和消失

时间:2019-06-10 21:22:38

标签: swift

我正在玩UIButtonisHidden属性。我想做的是这样的:

  • 使用button1启动应用。
  • 单击button1
  • 如果button2不可见,则使其出现。
  • 否则,使其消失。

如果按下button2,则使button1消失或出现,具体取决于它是否可见。

当我在启动时单击button1时,button2从不出现。是否需要刷新视图控制器以显示可用的新按钮?

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var button1: UIButton!
    @IBOutlet weak var button2: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        button2.isHidden = true

    }

    @IBAction func clickButton1() {
        if button2.isHidden == true {
            button2.isHidden = false
        }
        else { button2.isHidden = true}
    }

    @IBAction func clickButton2() {
        if button1.isHidden == false {
            button1.isHidden = true
        }
        else {button1.isHidden = false}
    }
}

3 个答案:

答案 0 :(得分:0)

检查网点和.xib / storyboard。也许您只是忘了链接视图以及相关操作。

您还可以简化方法。

更改此内容

 if self.button1.isHidden == false {
    self.button1.isHidden = true
 }
 else {
    self.button1.isHidden = false
 }

对此

self.button1.isHidden = !self.button1.isHidden

答案 1 :(得分:0)

您可以尝试这样:

    class ViewController: UIViewController {

    @IBOutlet var Btn1: UIButton!
    @IBOutlet var Btn2: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        Btn1.addTarget(self, action: #selector(Button1Pressed(_:)), for: .touchUpInside)
        Btn2.addTarget(self, action: #selector(Button2Pressed(_:)), for: .touchUpInside)
        Btn2.isHidden = true

    }

    @objc func Button1Pressed(_ sender: Any) {
        print("Button1Pressed")
        Btn2.isHidden.toggle()
    }
    @objc func Button2Pressed(_ sender: Any) {
        print("Button2Pressed")
        Btn1.isHidden.toggle()
    }
}

答案 2 :(得分:-2)

您在UI上所做的每个更改都必须在主线程上执行,因此您可以尝试类似的操作。...

@IBAction func clickButton1() {
        DispatchQueue.main.async {
            if self.button2.isHidden == true {
                self.button2.isHidden = false
            }
            else {
                self.button2.isHidden = true
            }

        }
    }

    @IBAction func clickButton2() {
        DispatchQueue.main.async {
            if self.button1.isHidden == false {
                self.button1.isHidden = true
            }
            else {
                self.button1.isHidden = false

            }
        }
    }

希望这对您有所帮助。...