首页 > 解决方案 > 按下后如何更改 UIBarButtonItem 的 titleTextAttributes?

问题描述

我有一个带有几个 UIBarButtons 的导航栏,我最初以 0.5 的 alpha 显示,并希望在按下后以 1 的 alpha 显示。我将这些属性存储在 normalAttributes 和 highlightAttributes 中。

我按以下方式设置按钮:

colorButton = UIBarButtonItem(title: "Colors", style: .plain, target: self, action: #selector(showColors))
colorButton.setTitleTextAttributes(normalAttributes, for: .normal)
colorButton.setTitleTextAttributes(highlightedAttributes, for: .selected)

这导致按钮短暂切换到突出显示的属性,这是预期的。但是,在按钮的操作 showColors 中,我然后执行以下操作:

textButton.setTitleTextAttributes(highlightedAttributes, for:[])

我也尝试过使用 .normal 而不是 []。这两种方法似乎都对按钮没有任何影响。对此的任何帮助将不胜感激。

标签: iosobjective-c

解决方案


我能想到的最简单的方法是使用自定义视图。意思是,创建一个单独UIButton的并在您的类中引用它(例如,let yourButton = UIButton())。初始化您的栏按钮项目,UIBarButtonItem(customView: yourButton)然后根据需要使用它。

请注意,您需要将action/target对添加到 上yourButton,而不是栏按钮项上。然后在您的action处理程序showColors中,根据您的情况,您可以更改yourButton.

您可以alpha直接切换,或者如果它只是我们正在谈论的文本,您可以这样做: yourButton.setTitleColor(yourColor, for: .normal)yourButton.setTitleColor(yourColorHalfAlpha, for: .selected)

然后在你的showColors,只需调用yourButton.isSelected = !yourButton.isSelected来切换外观。


推荐阅读