如何添加响应式 UIBarButtonItem?

How to Add Responsive UIBarButtonItem?

我想让自定义 UIBarButtonItem 通过更改自定义 UIImage 响应被点击。似乎没有 isTapped 属性 那么一种方法如何检查按钮是否已被选中?

如果无法从其他动态属性推断出选择状态,子类化 UIBarButtonItem 并添加一个选定标志(或您要维护的任何其他状态)。

子类化示例:UIBarButtonItem:https://github.com/cjwirth/RichEditorView/blob/master/RichEditorView/Classes/RichEditorToolbar.swift#L27

请注意,如果您只是设置背景图像或色调来指示按钮已被选中,您将能够直接比较这些属性以确定选择状态。

相关信息:https://developer.apple.com/documentation/uikit/uiappearance

您似乎在寻找 actionUIBarButtonItem initializer 包含一个 action 参数。您使用 add a #selector 为其添加功能。当点击 barButton 时,该函数将执行您想完成的任何操作。

// 1. Create a programmatic barButton
var changeImageButton: UIBarButtonItem!

override func viewDidLoad() {
    super.viewDidLoad()

    // 2. initialize the changeImageButton with a UIBarButtonItem. In the selector is where you can find out if the button was tapped
    changeImageButton = UIBarButtonItem(title: "Change Image", style: .plain, target: self, action: #selector(theButtonWasTapped))

    changeImageButton.tintColor = .orange
    navigationItem.rightBarButtonItem = changeImageButton
}

// 3. this will run when the changeImageButton is pressed
@objc func theButtonWasTapped(){

   print("my changeImageButton was tapped")

   // Add the code to change the UIImage here
}

我猜您想跟踪栏按钮是否被点击。 UIBarButton本身没有isSelected这样的属性。但是,您可以创建 UIBarButtonItem 并将自定义视图设置为 UIButton。

override func viewDidLoad() {
    super.viewDidLoad()

    let btnCustom = UIButton(type: .custom)
    btnCustom.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
    btnCustom.addTarget(self, action: #selector(tappedBarButton(sender:)), for: .touchUpInside)
    btnCustom.setImage(UIImage(named:"normalImage"), for: .normal)
    btnCustom.setImage(UIImage(named:"selectedImage"), for: .selected)

    btnCustom.imageEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5)

    let barBtnItem = UIBarButtonItem(customView: btnCustom)
    navigationItem.leftBarButtonItem = barBtnItem
}

@objc func tappedBarButton(sender: Any) {
    if let btnCustom = sender as? UIButton {
        btnCustom.isSelected = true // or as per your logic
    }
}