Question

I have in my app a navigation bar that have 2 buttons, one at each side. This button are used to change some important aspects of the app, like servers and stuff.

When the server is offline or have any problems the user is asked to change this option.

What i want is: How can i append a image to a button to call the user's attention? Something like this:

But the problem is: i don't even know how to start looking for this, how can i do it?

Was it helpful?

Solution

I recommend adding a UILabel as a subview of the button instead of an image, that way you can programmatically change it by using NSNotificationCenter from anywhere in your app.

- (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];
}

OTHER TIPS

For this initWithCustomView will work this with this you can add UIView objects there

 -(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];
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top