[英]Return string when button is pressed in Swift
有两个按钮。 按钮的作用是确定在搜索书籍时是按书名搜索还是按作者姓名搜索。
我做了一个部分,当按下authorNameFilterBtn
时bookTitleFilterBtn
被禁用。
var buttons: [UIButton] { return [bookTitleFilterBtn, authorNameFilterBtn] }
override func viewDidLoad() {
super.viewDidLoad()
bookTitleFilterBtn.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
authorNameFilterBtn.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
}
func updateButtonsAppearance(allButtons: [UIButton], selectedButton: UIButton) {
for button in allButtons {
let isSelected = button == selectedButton
let currentTitle = button.currentTitle ?? "-"
let title = NSAttributedString(string: currentTitle, attributes: [.foregroundColor: isSelected ? UIColor.white : UIColor.black])
button.setAttributedTitle(title, for: .normal)
button.setTitleColor(isSelected ? .white : .black, for: .normal)
button.backgroundColor = isSelected ? .red : .white
button.isHighlighted = isSelected
}
}
@objc func buttonClicked(_ sender: UIButton) {
DispatchQueue.main.async {
self.updateButtonsAppearance(allButtons: self.buttons, selectedButton: sender)
}
}
我要实现的是按下 bookTitleFilterBtn 时返回“book_title”,按下 authorNameFilterBtn 时返回“author_name”。
您可以在按钮按下方法中返回任何值,但没有帮助,因为返回值将返回到UIControl
class 并且您将无法访问它。
您可以将标签设置为按钮,当按下按钮时,您可以比较选项卡并确定按下了哪个按钮。 您还可以管理按钮选择状态以设置背景。 这是示例代码。
override func viewDidLoad() { super.viewDidLoad() bookTitleFilterBtn.tag = 1 bookTitleFilterBtn.setTitleColor(.black, for: .normal) bookTitleFilterBtn.setTitleColor(.white, for: .selected) bookTitleFilterBtn.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside) authorNameFilterBtn.tag = 2 authorNameFilterBtn.setTitleColor(.black, for: .normal) authorNameFilterBtn.setTitleColor(.white, for: .selected) authorNameFilterBtn.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside) } @objc func buttonClicked(_ sender: UIButton) { if sender.tag == 1{ bookTitleFilterBtn.isSelected = true authorNameFilterBtn.isSelected = false }else{ bookTitleFilterBtn.isSelected = false authorNameFilterBtn.isSelected = true } }
无需在main
线程中默认调用主块中的updateButtonsAppearance
作为触摸事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.