Reputation: 4837
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
@property (nonatomic, readwrite, strong) IBOutlet UIButton *uiLoginButton;
- (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
Reputation: 20021
If you are creating a button in nib you can change all the properties via nib itself.
Like this
OR
If you want to do it codewise since you are adding it via nib points to note
-setFrame:
method-setBackgroundcolor:
methodSo my .h
@property (nonatomic,strong) IBOutlet UIButton *uiLoginButton;
.m
[self.uiLoginButton setFrame:buttonRect];
[self.uiLoginButton setBackgroundColor:[UIColor redColor]];
Upvotes: 14
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
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