appearanceWhenContainedIn在UITableView和UINavigationController中的表现不如预期

3
我创建了一个简单的项目,其中包含一个UINavigationController、一个位于右侧的UIBarButtonItem和一个UITableView。为了测试,我想使用appearanceWhenContainedIn:方法将UINavigationController中的UIBarButtonItems颜色设为橙色,同时将UITableView中的UIButtons颜色设为红色。单独使用每个样式都可以正确地工作。但当我同时使用两者时,它不起作用。为什么呢?
场景1(在UINavigationController中给UIBarButtonItem上色):
[[UIBarButtonItem 
    appearanceWhenContainedIn:[UINavigationController class], nil] 
        setTintColor:[UIColor orangeColor]];

图片描述


场景2(在UITableView中为UIButton上色):

[[UIButton 
    appearanceWhenContainedIn:[UITableView class], nil] 
        setTintColor:[UIColor redColor]];

enter image description here


Scenario 3 (Combine them):

[[UIButton 
    appearanceWhenContainedIn:[UITableView class], nil] 
        setTintColor:[UIColor redColor]];
[[UIBarButtonItem 
    appearanceWhenContainedIn:[UINavigationController class], nil] 
        setTintColor:[UIColor orangeColor]];

输入图像描述


可通过此链接下载示例项目: https://www.dropbox.com/s/k7nabaqc9oso907/AppBugTesting.zip

更新: 在我继续诊断问题时,我发现如果我使用UIButton的"setBackgroundColor"将其设置为红色而不是setTintColor,它会显示红色背景UIBarButtonItem的橙色tint。出于某种原因,同时着色两个元素无法工作......仍然不确定原因。

3个回答

2
这是有效的:
[[UIButton 
    appearanceWhenContainedIn:[UITableView class], nil] 
        setTintColor:[UIColor redColor]];
[[UINavigationBar 
    appearanceWhenContainedIn:[UINavigationController class], nil] 
        setTintColor:[UIColor orangeColor]];

当然,这可能会使一些你不想要的东西变成橙色。

谢谢,这确实可以满足我的需求。但你说得对,这会导致其他不想变成橙色的对象也变成橙色。我很好奇是否还有其他解决方法。目前看来,这个答案是最好的。 - Kivak Wolf
你需要单独处理那些对象,以防它们变成橙色。或者,嘿,你手动创建这个工具栏按钮项,为什么不在创建时将其色调设置为橙色呢? - matt
所以,在这个演示中我这样做。但是在我目前正在工作的项目中,我正在使用类似的代码从委托中的单个位置更改应用程序的样式,其中我设置了所有颜色。这主要是因为计划重新设计应用程序以适应多种用途,而不必重新发明轮子。 - Kivak Wolf
是的,我明白。但我的意思是,这个有漏洞,所以最基本的解决方法是手动设置单个条形按钮项的色调颜色。哦,还请向苹果提交一个错误报告!你的例子非常有说服力,因为你可以证明它可以在一个或另一个外观调用中工作,但不能同时使用两个。 - matt

1
我会创建“空白”的UITableViewUINavigationController子类来引用,以避免意外更改其他按钮的外观。
[[UIButton 
    appearanceWhenContainedIn:[MyTableView class], nil] 
        setTintColor:[UIColor redColor]];
[[UINavigationBar 
    appearanceWhenContainedIn:[MyNavigationController class], nil] 
        setTintColor:[UIColor orangeColor]];

0

这在iOS 7的测试期间是正确的,但现在不再是这样了。他们收到了很多关于此事的投诉并进行了更改。 :) - matt
那个在哪里有记录? - Chris Flesner
它是由现实所记录的。:) setTintColor: 在外观代理上确实起作用,正如OP的示例清楚地证明的那样。以前,它不仅不起作用,甚至无法编译。 - matt
你所声称的更改在我链接的文档中没有提到。在UIAppearance协议参考中也没有提到,如果你按照此处列出的获取符合协议的方法和属性列表的说明进行操作,tintColor也不会显示:https://gist.github.com/mattt/5135521 - Chris Flesner
它在某些情况下能够工作并不意味着它是受支持的行为。如果它没有出现在任何文档或公共头文件中,那么根据定义,它是未记录的。 - Chris Flesner
如果您尝试在外观代理上使用setTintColor:,则应用程序以前会崩溃:Terminating app due to uncaught exception 'NSInvalidArgumentException',reason: '-setTintColor: is not allowed for use with the appearance proxy. Perhaps you want to use the barTintColor property.' 他们取消了这个限制,表明现在是允许的。我同意它的状态有些奇怪,而且色调颜色在很多方面都存在问题(苹果也知道)。但告诉OP他不能做他想做的事情是错误的。它可能存在缺陷,但尝试它并不违法。 - matt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接