为自定义UIView定义“样式”初始值设定项

时间:2013-07-27 22:33:44

标签: ios objective-c cocoa-touch uiview

我在一些地方重新使用UIView子类,但有时需要布局略有不同 - 有时子视图是水平布局的,有时是垂直布局的。

我想以某种方式复制UITableView和其他UIViews使用的'initWithStyle'方法。应该可以'initWithStyle'但是也应该有一个默认值。也可以使用setStyle更改样式。

实现这一目标的步骤是什么?我尝试定义一个枚举和一个新的初始化器,但我不在这里。

1 个答案:

答案 0 :(得分:0)

听起来你走在正确的轨道上,所以我不确定自己有多大帮助。创建公共初始值设定项和公共setStyle方法。对不起打字错误。我是在没有编辑的情况下这样做的。

·H

-(id)initWithFrame:(CGRect)frame;
-(id)initWithFrame:(CGRect)frame style:(MyStyleEnum)myStyleEnum;
-(void)setStyle:(MyStyleEnum)myStyleEnum;

的.m

 //here's your default method which passes your default style to your custom init method
-(id)initWithFrame:(CGRect)frame {
    return [self initWithFrame:frame style:myStyleEnumDefault];
}

//your custom init method that takes a style
-(id)initWithFrame:(CGRect)frame style:(MyStyleEnum)myStyleEnum {
    self = [super initWithFrame:frame];

    if(self) {
        [self setStyle:myStyleEnum];
    }

    return self;
}

//this can be called after initialization
-(void)setStyle:(MyStyleEnum)myStyleEnum {
    //make sure the view is clear before you layout the subviews
    //[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];//not needed adjusting constraints and not repopulating the view

    //change the view constraints to match the style passed in
    //the acutally changing, should probably be done in separate methods (personal preference) 
    if(myStyleEnum == myStyleEnumDefault) {
       //change constraints to be the default constraints
    } else if(myStyleEnum == myStyleEnumA) {
        //change constraints to be the A constraints
    } else if(myStyleEnum == myStyleEnumB) {
         //change constraints to be the B constraints
    }

}