首页 > 解决方案 > 为什么设置 UIBarButtonItem 的 primaryAction 属性会更改其图像?

问题描述

编辑:这已解决,请参阅帖子底部。

在使用便捷初始化程序初始化按钮后,primaryAction我希望为 a设置 a 。UIBarButtonItem init(title:image:primaryAction:menu:)

当我这样做时,图像属性会被nil删除,如下所示:

let settingsButton = UIBarButtonItem(title: nil, image: gearImage, primaryAction: nil, menu: nil)

// Before - settingsButton.image is non-nil, as expected
settingsButton.primaryAction = UIAction(...)

// After - settingsButton.image is nil - unexpected

查看 UIKit 标头文档,我注意到了这一点:

/// Set the primaryAction on this item, updating the title & image of the item if appropriate 
(primaryAction is non-nil, and this is not a system item). 
When primaryAction is non-nil, the target & action properties are ignored. 
If primaryAction is set to nil, the title & image properties are left unchanged.

设置此项目的主要操作,如果合适,更新项目的标题和图像

所以我认为这个事件导致image为 nil,但是......为什么会触发?什么目的?

我可以通过在设置image后设置属性来解决这个问题primaryAction,例如:

let settingsButton = UIBarButtonItem(title: nil, image: gearImage, primaryAction: nil, menu: nil)

settingsButton.primaryAction = UIAction(...)
settingsButton.image = gearImage

但这有效地使便利初始化器在这种情况下无用。


编辑:感谢@Sweeper 指出这一点。UIBarButtonItem似乎使用and titlefrom imageaUIAction来更新其图像和标题,然后设置primaryAction属性。

UIAction您可以使用初始化程序创建一个init(title:image:identifier:discoverabilityTitle:attributes:state:handler:)并将您的图像传递给该操作以使其呈现,如下所示:

settingsButton.primaryAction = UIAction(title: "", 
                                        image: gearImage, 
                                        identifier: nil, 
                                        discoverabilityTitle: nil, 
                                        attributes: .disabled, 
                                        state: .mixed, handler: { (action) in
    // Do something here
})

因为在我的例子中,我使用了UIAction(handler:)初始化程序,这将设置UIAction'titleimage属性 nil,这会导致UIBarButtonItem' 的图像变为 nil。

标签: iosswiftuikit

解决方案


推荐阅读