UIBarButtonItem色调不起作用

时间:2017-01-19 14:11:49

标签: ios cocoa-touch ios10 uibarbuttonitem tintcolor

我最近注意到,tintColor属性的行为在最近的iOS 10更新中发生了重大变化。

我有一个以前完美运行的代码,现在根本无法运行。

在我的一个应用程序中,我有一组UIBarButtonItem s,它们被添加到视图控制器的toolbarItems数组中。它们显示得很好。

但是,在某些时候,我想要更改某些项目的色调颜色以响应用户操作。代码很简单:

flagButton.tintColor = [UIColor redColor];

此代码以前曾用过,但现在它不起作用!我已经验证了对UIBarButtonItem的引用存在,并且执行了这行代码。但是,色调颜色没有改变。

tintColor属性的描述中,它说:

  

要在此属性更改时刷新子视图渲染,请覆盖tintColorDidChange()方法。

我尝试添加tintColorDidChange方法,但未调用它。我在这个阶段的假设是,一旦tintColor被更改,我的按钮就不会自动刷新。

有人可以帮忙找到手动刷新的方法吗?该按钮是带有图像的标准UIBarButtonItem

更新1

实际上我注意到,如果我更改工具栏的tintColor而不是单个项目代码正在运行。似乎由于某种原因,在单个项目上设置色调颜色不再有效。有谁知道为什么会这样?

更新2

感谢matt的暗示,我能够找到问题的根源。它是由启动应用程序时执行的代码引起的:

[[UITableViewCell appearance] setTintColor:[ColourTheme sharedTheme].navBackground];

现在,我完全不知道为什么这一行导致了UIBarButtonItem色调的问题...这可能是因为它在UIAppearance中引入了一些含糊之处。无论如何,由于我自己不再需要这条线,我可以轻松地将其移除。我仍然会打开我的问题,因为我认为这种行为非常奇怪,所以在某种程度上,这个问题仍然没有答案。

正如附加信息一样 - 遇到这些问题的视图控制器中包含一个表格视图。

5 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,最后通过以下步骤解决了问题:

1)创建条形按钮项目的插座。我被称为“closeButton” 2)编写以下代码:

override func viewWillAppear(animated: Bool) {
  let barButtonAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
  closeButton.setTitleTextAttributes(barButtonAttributes, for: .normal)
}

请务必将代码放在viewWillAppear中,因为这会覆盖UIAppearance的默认设置。

答案 1 :(得分:1)

我无法重现任何问题。在这里你可以看到我们正在交替红色和绿色之间的右边栏按钮项目的色调颜色;这可以通过直接在代码中设置条形按钮项tintColor来完成:

enter image description here

        let c = self.replyButton.tintColor
        if c == UIColor.red {
            self.replyButton.tintColor = .green
        } else {
            self.replyButton.tintColor = .red
        }

因此,我得出结论,您所看到的问题是由您未告诉我们的其他事情引起的。

答案 2 :(得分:1)

所以在我的情况下,这一行

UIActivityIndicatorView.appearance.tintColor = FlatWhite;

在didFinishLaunchingWithOptions中设置将所有UIBarItemItems.tintColor更改为默认蓝色,除了在父栏上设置色调颜色之外,无法以其他方式更改它...

当我评论此行时,取消注释它停止工作时一切正常。对我来说,这是IOS框架中的明显错误。这很难预测,因为在其他情况下它没什么不同。

答案 3 :(得分:0)

我猜您使用的是UIImageRenderingMode.alwaysOriginal,它会导致问题。

public enum UIImageRenderingMode : Int {

     case automatic // Use the default rendering mode for the context where the image is used
     case alwaysOriginal // Always draw the original image, without treating it as a template
     case alwaysTemplate // Always draw the image as a template image, ignoring its color information

}

使用.alwaysTemplate

答案 4 :(得分:0)

如果导航控制器中嵌入了View Controller,请执行以下操作-在导航控制器中,检查导航栏的View / Tint属性。我发现这将覆盖View Controller中放入ViewDidLoad的所有代码。

相关问题