swift - 如何在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)
}
错误:
无法将“字符串”类型的值转换为预期的条件类型“布尔”
解决方案
您需要检查 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()
其中显示了不断变化的按钮标题。
你应该能够从这里得到你需要的东西。
推荐阅读
- javascript - 从输入 Laravel 插入多个数据
- go - 子文件夹调用文件夹 Golang
- c++ - 一般来说,不在控制语句/函数中使用成员函数,而是将它们的值存储在变量中然后使用它是最明智的吗?
- javascript - 异步扩展破坏了 GNOME Shell
- android - Android 11 MediaStore:可以将内部存储中的文件添加到媒体商店以供其他应用了解吗?说mp3
- javascript - 一段时间后如何删除此消息(Discord.js)
- c++ - 如何从 NodeJS 在 Heroku 上运行已编译的可执行文件
- python - 如何绘制分层列中的数据?
- jquery - 将 TinyMCE 5 与 Django 管理员 TabularInline 一起使用
- python - 比较两个中文单词是否相等