将图像添加到UINavigationBar中的UIButton

问题描述:

我在我的应用程序中有一个导航栏,它有两个按钮,每个按钮一个。此按钮用于更改应用程序的某些重要方面,例如服务器和内容。将图像添加到UINavigationBar中的UIButton

当服务器处于脱机状态或遇到任何问题时,系统会要求用户更改此选项。

我想要的是:如何将图像追加到按钮来唤起用户的注意?事情是这样的:

但问题是:我甚至不知道如何开始寻找这个,我该怎么办呢?

+0

每当时机成熟时,您可以创建图像和更改按钮的图像。 – user523234

+0

问题是按钮的标题会改变很多,所以我真的不想依赖那些很多的图片,我只想将“alert”图片添加到按钮 –

我建议添加一个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]; 
} 
+0

该按钮位于导航栏内,wouldn那是不是让按钮切掉了所有的边界?我会检查这个,尽快回复 –

+0

它应该仍然有效。我上面使用的代码实际上是一个UIBarButtonItem的自定义UIView我做的。请参阅更新的答案。您需要手动播放帧值,以便执行您想要执行的操作,以及对您最合适的操作。 – klcjr89

+0

不要忘记dealloc方法。请参阅上面的答案。 – klcjr89

对于这个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'' –