将图像添加到UINavigationBar中的UIButton
问题描述:
我在我的应用程序中有一个导航栏,它有两个按钮,每个按钮一个。此按钮用于更改应用程序的某些重要方面,例如服务器和内容。将图像添加到UINavigationBar中的UIButton
当服务器处于脱机状态或遇到任何问题时,系统会要求用户更改此选项。
我想要的是:如何将图像追加到按钮来唤起用户的注意?事情是这样的:
但问题是:我甚至不知道如何开始寻找这个,我该怎么办呢?
答
我建议添加一个UILabel作为按钮的子视图而不是图片,这样你可以通过在应用程序的任何位置使用NSNotificationCenter以编程方式更改它。
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(updateButtonLabel:)
name:@"UpdateButtonLabel" object:nil];
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]
button.frame = CGRectMake(0, 0, 35, 35);
[button addTarget:self action:@selector(buttonMethods:) forControlEvents:UIControlEventTouchUpInside];
[button setTintColor:[UIColor companyBlue]];
[button setTitle:@"Button" forState:UIControlStateNormal];
self.buttonLabel = [[UILabel alloc]initWithFrame:CGRectMake(18,-7,18,18)];
self.buttonLabel.textColor = [UIColor whiteColor];
self.buttonLabel.backgroundColor = [UIColor companyRed];
self.buttonLabel.font = [UIFont systemFontOfSize:13.0];
self.buttonLabel.layer.cornerRadius = 9;
self.buttonLabel.layer.masksToBounds = YES;
self.buttonLabel.textAlignment = NSTextAlignmentCenter;
self.buttonLabel.text = @"!";
[button addSubview:self.buttonLabel];
}
- (void)updateButtonLabel:(NSNotification *)notification
{
NSString *labelString = notification.object;
// Post a notification from any view controller with a string with no characters to hide the label:
if (newString.length < 1)
{
self.buttonLabel.hidden = YES;
}
else
{
self.buttonLabel.text = labelString;
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
答
对于这个initWithCustomView
将工作这与此您可以添加UIView
对象有
-(void)setRightBarButton{
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(0, 0, 35, 35);
[button addTarget:self action:@selector(buttonMethods:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Button" forState:UIControlStateNormal];
self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:button];
}
+0
对不起,问题不在于将'UIButton'添加到' 'UINavigationBar''关于添加一个''view''到''UIButton''已经在''UINavigationBar'' –
每当时机成熟时,您可以创建图像和更改按钮的图像。 – user523234
问题是按钮的标题会改变很多,所以我真的不想依赖那些很多的图片,我只想将“alert”图片添加到按钮 –