2013-07-27 2 views
1

몇 군데에서 UIView 하위 클래스를 재사용하고 있지만 경우에 따라 레이아웃을 약간 다르게해야합니다. 때로는 하위 뷰가 때로는 세로로 배치됩니다.사용자 정의 UIView에 대한 '스타일'이니셜 라이저 정의

저는 UITableView와 다른 UIView가 사용하는 'initWithStyle'접근법을 어떻게 든 복제하고 싶습니다. 'initWithStyle'이 가능해야하지만 기본값도 있어야합니다. setStyle을 사용하여 스타일을 변경하는 것도 가능해야합니다.

이 작업을 수행하기위한 단계는 무엇입니까? 나는 열거 형과 새로운 이니셜 라이저를 정의하려고 시도했지만, 여기서 나는 깊이 빠져있다.

답변

0

당신이 옳은 길을 걷고있는 것처럼 들리므로 내가 얼마나 도움이되는지 확신 할 수 없습니다. public initializer 및 public 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 
    } 

} 
+0

정말 감사합니다. autolayout을 사용하고 있기 때문에 setStyle에서 제약 조건을 제거하고 추가 할 수 있을지 궁금하다. 서브 뷰 자체 대신에? –

+1

죄송합니다. xib 또는 스토리 보드에 대한 많은 경험이 없습니다. 당신이 할 수있는 것처럼 보이고 그것은 너무 많은 문제가되지 않을 것입니다. 다음은 여러분이 묻는 질문을 다루는 또 다른 질문에 대한 링크입니다. http://stackoverflow.com/questions/14215641/autolayout-seems-not-working-when-changing-view-dimensions-programmatically이 스레드로 핑을 느껴보십시오. 또 다른 질문. – JeffRegan

+1

또한 뷰를 다시 생성하는 대신 제약 조건을 조정하기 때문에 필자는 수정 (잘못된 것임)하고 수퍼 뷰 호출에서 제거를 주석 처리합니다 (이 사실을 알면 도움이되지만 실제로는 관련이 없습니다). – JeffRegan

관련 문제