如何在 swift 中使用三元运算符设置 UIButton 标题

How to set UIButton title using ternary operator in swift

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

最初的标题应该是 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)
}

错误:

Cannot convert value of type 'String' to expected condition type '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)
}

如果您想查看更大的示例,请在 playground 中尝试:

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()

其中显示了不断变化的按钮标题。

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