Reputation: 43
Is there an equivalent padding for UIButton, just like in CSS?.
I seem to have a problem with small buttons so I want to expand the button size for it to be easily clickable.
I made a work around code to resize a UIButton and have the contents remain as they are supposed to be:
- (void)adjustButtonView:(UIButton *)button toSize:(CGSize)size
{
CGRect previousFrame = button.frame;
CGRect newFrame = button.frame;
newFrame.size = size;
CGFloat adjustX = (size.width - previousFrame.size.width)/2;
CGFloat adjustY = (size.height - previousFrame.size.height)/2;
newFrame.origin.x = previousFrame.origin.x - adjustX;
newFrame.origin.y = previousFrame.origin.y - adjustY;
button.frame = newFrame;
UIEdgeInsets edgeInsets = UIEdgeInsetsMake(adjustY, adjustX, adjustY, adjustX);
button.contentEdgeInsets = edgeInsets;
}
I'm just wondering if there is an easier way to expand the UIButtons.
Upvotes: 4
Views: 4045
Reputation: 9039
Well actually, there is one stupidly simplistic way to expand the width of UIButtons if you don't want to mess with subclassing.... try this:
[b setTitle:[NSString stringWithFormat:@" %@ ", @"Title"] forState:UIControlStateNormal];
Upvotes: 1
Reputation: 348
I don't think there's an easier way than what you did. But we can make your code better by moving the method to a UIButton category.
UIButton+Resize.h
@interface UIButton (Resize)
- (void)adjustToSize:(CGSize)size;
@end
UIButton+Resize.m
@implementation UIButton (Resize)
- (void)adjustToSize:(CGSize)size
{
CGRect previousFrame = self.frame;
CGRect newFrame = self.frame;
newFrame.size = size;
CGFloat adjustX = (size.width - previousFrame.size.width)/2;
CGFloat adjustY = (size.height - previousFrame.size.height)/2;
newFrame.origin.x = previousFrame.origin.x - adjustX;
newFrame.origin.y = previousFrame.origin.y - adjustY;
self.frame = newFrame;
UIEdgeInsets edgeInsets = UIEdgeInsetsMake(adjustY, adjustX, adjustY, adjustX);
self.contentEdgeInsets = edgeInsets;
}
@end
Upvotes: 2
Reputation: 20410
No, there's nothing like CSS or style sheets for iOS, if you want to resize a button you'll have to do it manually setting the frame.
In order to automatize this task, you can create a button and subclass it, or use categories.
Upvotes: 0