JoJ*_*oJo 5 iphone cocoa-touch ios
我正在使用UIAppearance设计 UINavigationBar 的样式。我希望所有后退按钮都有灰色文本,所有 rightBarButtonItems 都有绿色文本(颜色是假设的)。由于默认情况下这两个按钮都是 UIBarButtonItems,因此 UIAppearance 无法区分这两个按钮。所以我决定对 UIBarButtonItem 进行子类化,将其命名为 ActionBarButtonItem。我在需要 rightBarButtonItem 的任何地方都使用这个新子类。
UIBarButtonItem* done = [[ActionBarButtonItem alloc]
initWithTitle:@"Done"
style:UIBarButtonItemStyleDone
target:self
action:@selector(onDonePress)];
self.navigationItem.rightBarButtonItem = done;
[done release];
Run Code Online (Sandbox Code Playgroud)
NSDictionary* buttonStyle = [NSDictionary
dictionaryWithObjects:[NSArray
arrayWithObjects:
[UIColor grayColor],
, nil
]
forKeys:[NSArray
arrayWithObjects:
UITextAttributeTextColor,
nil
]
];
NSDictionary* actionStyle = [NSDictionary
dictionaryWithObjects:[NSArray
arrayWithObjects:
[UIColor greenColor],
nil
]
forKeys:[NSArray
arrayWithObjects:
UITextAttributeTextColor,
nil
]
];
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationController class], nil]
setTitleTextAttributes:buttonStyle
forState:UIControlStateNormal
];
[[ActionBarButtonItem appearanceWhenContainedIn:[UINavigationController class], nil]
setTitleTextAttributes:actionStyle
forState:UIControlStateNormal
];
Run Code Online (Sandbox Code Playgroud)
理论上,灰色文本将应用于所有 UIBarButtonItems。然后,我仅使用 ActionBarButtonItems 的绿色文本覆盖该灰色文本。最终的结果并不如预期。由于未知原因,每个UIBarButtonItem 都会显示绿色文本。为什么?


您正在子类化,UIBarButton所以我最初的想法是,当您调用appearanceWhenContainedIn结果时ActionBarButtonItem,就是对超类的调用appearanceWhenContainedIn,因此这就是发生这种情况的原因。这并不理想,但您可以更改已加载的视图上左侧和右侧项目的外观,或者视图将出现在每个视图中。
NSDictionary* buttonStyle = [NSDictionary
dictionaryWithObjects:[NSArray
arrayWithObjects:
[UIColor blueColor],nil]
forKeys:[NSArray
arrayWithObjects:
UITextAttributeTextColor,
nil
]
];
NSDictionary* actionStyle = [NSDictionary
dictionaryWithObjects:[NSArray
arrayWithObjects:
[UIColor greenColor],
nil
]
forKeys:[NSArray
arrayWithObjects:
UITextAttributeTextColor,
nil
]
];
[self.navigationItem.leftBarButtonItem setTitleTextAttributes:buttonStyle forState:UIControlStateNormal];
[self.navigationItem.rightBarButtonItem setTitleTextAttributes:actionStyle forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)
您还可以选择将其放在像您的应用程序委托这样的地方,以便您可以使用 更简单地访问它[[UIApplication sharedApplication].delegate setBarButtonColors]。另一种选择可能是UINavigationBar.