首页 > 解决方案 > 如何在swift中使用三元运算符设置UIButton标题

问题描述

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

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

错误:

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

标签: swiftbutton

解决方案


您需要检查 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()

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

在此处输入图像描述

你应该能够从这里得到你需要的东西。


推荐阅读