1

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

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

实现这一目标的步骤是什么?我尝试定义一个枚举和一个新的初始化程序,但我在这里超出了我的深度。

4

1 回答 1

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
    }

}
于 2013-07-27T23:06:24.450 回答