【问题标题】:How to set UIButton title using ternary operator in swift如何在swift中使用三元运算符设置UIButton标题
【发布时间】:2021-07-19 15:28:14
【问题描述】:

我有一个按钮,我需要在其中显示两个标题..

最初标题应该是Login with Phone,如果我点击按钮,它应该更改为Login with Email

怎么做?

我试过这样

class LoginVC: UIViewController{

@IBOutlet weak var changeOtpBtn: UIButton!


override func viewDidLoad() {
    super.viewDidLoad()
    
    self.changeOtpBtn.setTitle("Login with phone" ? "Login with Email" : "AELogin with phoneD", for: .normal)
}

错误:

无法将“字符串”类型的值转换为预期的条件类型“布尔”

【问题讨论】:

  • 先写成“normal”if,然后再转换成三元if。你会看到你的问题。
  • @Larme,怎么做..你能发布答案吗
  • if changeOtpBtn.title(for: .normal) == ""Login with Email") { ... } else { ... },这就是你想要的,不(或类似的东西)?您想获取当前标题并进行比较,因此请先检索它。但我会避免比较标题,而是保留一个布尔值或枚举值......

标签: swift button


【解决方案1】:

您需要检查 Bool,而不是字符串。如果您添加一个变量来保存状态,那么您可以使用

class LoginVC: UIViewController{

@IBOutlet weak var changeOtpBtn: UIButton!
var shouldLoginWithEmail = false


override func viewDidLoad() {
    super.viewDidLoad()
    
    self.changeOtpBtn.setTitle(shouldLoginWithEmail ? "Login with Email" : "AELogin with phoneD", for: .normal)
}

如果您想查看更大的示例,请在操场上试试这个:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    var shouldLoginWithEmail = false

    lazy var button: UIButton = {
        UIButton()
    }()

    @objc func buttonClicked() {
        print("tapped")
        shouldLoginWithEmail.toggle()
        setLoginButtonTitle()
    }

    func setLoginButtonTitle() {
        button.setTitle(shouldLoginWithEmail ?
                            "Login with Email" :
                            "AELogin with phoneD",
                        for: .normal)
    }


    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        button.addTarget(self, action: #selector(buttonClicked),
                         for: .touchUpInside)
        button.frame = CGRect(x: 100, y: 200, width: 200, height: 20)
        button.setTitleColor(.blue, for: .normal)
        setLoginButtonTitle()

        view.addSubview(button)
        self.view = view
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

显示变化的按钮标题。

你应该可以从这里得到你需要的东西。

【讨论】:

  • 当我点击changeOtpBtn时标题没有改变,为什么?我已经完成了你的代码
  • 因为该代码在viewDidLoad()中,所以在调用tap的IBAction时需要更改标题。 self.changeOtpBtn.setTitle(_:for:) 并不意味着“每当我决定时,我不知道触发器,更改标题”,不是,它是在应用程序读取该行时更改它。目前在viewDidLoad()阅读。
  • @Larme 如果我在 changeOtpBtn 的 IBAction 中移动这一行 self.changeOtpBtn.setTitle(shouldLoginWithEmail ? "Login with Email" : "AELogin with phoneD", for: .normal) 那么标题只会更改一次
  • @Larme 我需要喜欢.. 如果我继续点击.. 标题应该交替更改.. 我想要这样.. 怎么做
  • “下一个价值”应该是什么?你不应该改变shouldLoginWithEmail:` shouldLoginWithEmail = 的值吗?应该LoginWithEmail`?您缺少信息。
猜你喜欢
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-07
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
  • 2021-09-11
相关资源
最近更新 更多