Swift - 如何隐藏标签,然后在按下按钮后使其永远显示?

标签 swift uibutton uilabel

我试图让标签开始隐藏,然后在按下按钮后让标签永远显示,即使在您注销/重新启动应用程序后也是如此。现在,它在我单击按钮后显示,但在我注销/重新启动后变为隐藏。这是我的代码:

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    hidePercent()
}

var didTapOptionsButtonForCell: ((YourPollsCell) -> Void)?

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state

    let percentColor = UIColor(red: 115/255, green: 21/255, blue: 54/255, alpha: 1.0).cgColor
    pollText1Percent.layer.borderColor = percentColor
    pollText1Percent.layer.borderWidth = 2
    pollText2Percent.layer.borderColor = percentColor
    pollText2Percent.layer.borderWidth = 2
}

func hidePercent() {
    pollText1Percent.isHidden = true
    pollText2Percent.isHidden = true
}

@IBAction func reportButtonTapped(_ sender: UIButton) {
    didTapOptionsButtonForCell?(self)
}

@IBAction func pollText1ButtonTapped(_ sender: UIButton) {
    delegate?.didTapVoteButton(sender, pollNum: 1, on: self)

    pollText1Percent.isHidden = false
    pollText2Percent.isHidden = false
}

@IBAction func pollText2ButtonTapped(_ sender: UIButton) {
    delegate?.didTapVoteButton(sender, pollNum: 2, on: self)

    pollText1Percent.isHidden = false
    pollText2Percent.isHidden = false
}

最佳答案

点击按钮时,您可以向 UserDefaults 添加一个值。

UserDefaults.standard.set(value: true, forKey: "specialButtonWasTapped")

然后在应用程序启动时在 Controller 中检查此值并设置 isHidden 属性。

if let wasTapped = UserDefaults.standard.value(forKey: "specialButtonWasTapped") {
    specialLabel.isHidden = !wasTapped    // false
}
else {
    specialLabel.isHidden = true
}

或者清理这个想法

UserDefaults.standard.set(value: false, forKey: "labelShouldBeHidden")

然后你可以使用 nil 合并运算符设置 isHidden 属性

specialLabel.isHidden = (UserDefaults.standard.value(forKey: "labelShouldBeHidden") as? Bool) ?? true

关于Swift - 如何隐藏标签,然后在按下按钮后使其永远显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45603805/

相关文章:

swift - 获取 iCloud Drive 的内容

Swift 期待声明但已经声明

ios - 如何在 iOS 中使用 swift 重新定位 View ?

ios - 为 swift 2 中的按钮创建可缩放的三行菜单导航图标

iphone - 在iOS中,可以通过alloc和initWithFrame添加UIButton吗?

ios - 如何在自定义 UIToolbar 类初始化的闭包中添加 UIButton 操作?

ios - 如何为闭包分配内存及其存储机制是什么?

ios - 为什么在完成 block 中更改 .text 字段时 UITextField 和 UILabel 不更新?

ios - UILabel 上的 instrictContentSize 在不同的实例中返回不同的值

ios - 如何对齐段落中的 UILabel 文本