H.Rabiee
H.Rabiee

Reputation: 4837

Another UIButton background color issue

Yet another simple issue with changing the background color of a UIButton. So I have figured after searching a bit that a common way is to either create an image or subview.

I have created a button in storyboard and connected it to an outlet. In my VC class I have the following

.h

@property (nonatomic, readwrite, strong) IBOutlet UIButton *uiLoginButton;

.m

- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%s and frame rect %@", __PRETTY_FUNCTION__, self.uiLoginButton); //here uiloginbutton does not have any size!

CGRect buttonRect = CGRectMake(50, 50, 100.0, 100.0);

self.uiLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.uiLoginButton.frame = buttonRect;
self.uiLoginButton.backgroundColor = [UIColor redColor];
NSLog(@"%s and frame rect %@", __PRETTY_FUNCTION__, self.uiLoginButton);    
}

No I have set the values in CGRectMake randomly because the IBOutlet button's frame is 0. How come?

What is the correct way to actually change the button's color?

Upvotes: 5

Views: 8117

Answers (3)

Lithu T.V
Lithu T.V

Reputation: 20021

If you are creating a button in nib you can change all the properties via nib itself. Like this enter image description here

OR

If you want to do it codewise since you are adding it via nib points to note

  • No need for an initialization.since it is a property from IB.
  • Just directly provide frame via IB or in code via -setFrame: method
  • To set color, you can use -setBackgroundcolor: method

So my .h

@property (nonatomic,strong) IBOutlet UIButton *uiLoginButton;

.m

[self.uiLoginButton setFrame:buttonRect];
[self.uiLoginButton setBackgroundColor:[UIColor redColor]];

Upvotes: 14

LE SANG
LE SANG

Reputation: 11005

You need to test all method in referent to understand: https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIButton_Class/UIButton/UIButton.html

If you draw UIButton in storyBoard,NSLog frame in viewDidAppear.

If you use RounRect type and want to change color, use storyBoard, don't use code.

IF you use Custom type, use Image Background, not set color:

[button setBackgroundImage:(UIImage *) forState:UIControlStateNormal];

Upvotes: 1

Nick C
Nick C

Reputation: 645

you are overriding the value of self.uiLoginButton

remove these lines

CGRect buttonRect = CGRectMake(50, 50, 100.0, 100.0);

self.uiLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.uiLoginButton.frame = buttonRect;

Upvotes: 0

Related Questions