重用UIButton风格

时间:2014-08-18 23:26:52

标签: ios objective-c cocoa-touch uibutton

我有几个具有相同风格的UIButton,但有时它们有不同的颜色,有时它们有不同的宽度。但是,我讨厌为一个只需要略微不同颜色的新按钮创建一个单独的类,所以我认为必须有一种方法来设置按钮的样式,并将颜色和高度作为属性。之后我成像它就像导入UITableView的数据源/委托一样。

这是一个更具体的问题:有没有办法为UIButton创建一个带有宽度和高度等参数的类,是否可以将这种类声明为UIButton?

2 个答案:

答案 0 :(得分:0)

这完全没问题。创建UIButton的类别或子类。定义自定义初始化方法,如- (instancetype)initWithColor:(UIColor *)color size:(CGSize)size。在init方法中调用self = [super initWithFrame:CGRectZero],然后在self上设置这些属性。

答案 1 :(得分:0)

关于常用样式,您可以创建一个返回样式按钮的方法。

- (UIButton *)styledButtonWithFrame:(CGRect)frame
{
    UIButton *btn = [[UIButton alloc] initWithFrame:frame];
    [btn setBackgroundColor:[UIColor redColor]];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    return btn;
}

您可以创建styledButton的实例

UIButton *styledBtn = [self styledButtonWithFrame:CGRectMake(0, 0, 10, 10)];

第二个问题,你可以使用类别。

@interface UIView (BKExpansion)
@property (nonatomic, assign) CGFloat frameX;
@property (nonatomic, assign) CGFloat frameHeight;
@end

@implementation UIView (BKExpansion)
- (CGFloat)frameX
{
    return self.frame.origin.x;
}

- (void)setFrameX:(CGFloat)frameX
{
    CGRect frame_ = self.frame;
    frame_.origin.x = frameX;
    self.frame = frame_;
}

- (CGFloat)frameWidth
{
    return self.frame.size.width;
}

- (void)setFrameWidth:(CGFloat)frameWidth
{
    CGRect frame_ = self.frame;
    frame_.size.width = frameWidth;
    self.frame = frame_;
}
@end

您可以添加frameY,frameBottom等。

如果要更改frameX或frameWidth,只需使用

即可
[styledBtn setFrameY:30];