是否有与UIButton等效的填充,就像在CSS中一样?。
我似乎遇到了小按钮的问题,因此我想扩展按钮大小,以便轻松点击。
我围绕代码调整UIButton的大小,让内容保持原样:
- (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;
}
我只是想知道是否有更简单的方法来扩展UIButtons。
答案 0 :(得分:2)
我认为这比你做的更简单。但是我们可以通过将方法移动到UIButton类别来使代码更好。
的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
答案 1 :(得分:1)
实际上,如果你不想搞乱子类,有一种愚蠢的简单方法可以扩展UIButton的宽度....试试这个:
[b setTitle:[NSString stringWithFormat:@" %@ ", @"Title"] forState:UIControlStateNormal];
答案 2 :(得分:0)
不,没有类似iOS的CSS或样式表,如果你想调整一个按钮,你必须手动设置框架。
为了使此任务自动化,您可以创建一个按钮并将其子类化,或使用类别。