2016-10-22 4 views
1

이렇게 질문하는 몇 가지 질문이 있지만 아무도 제대로 질문하지 않았습니다.initWithCoder에서 1000x1000보기 :

이 구현에서는 UIView 기반 클래스 인 사용자 지정 진행률 표시 줄을 사용하고 있습니다.

@implementation MCProgressBarView { 
    UIImageView * _backgroundImageView; 
    UIImageView * _foregroundImageView; 
    CGFloat minimumForegroundWidth; 
    CGFloat availableWidth; 
} 

- (instancetype)initWithCoder:(NSCoder *)aDecoder { 
    self = [super initWithCoder:aDecoder]; 
    // [self bounds] is 1000x1000 here... what? 
    if (self) [self initialize]; 
    return self; 
} 


- (instancetype)initWithFrame:(CGRect)frame { 
    self = [super initWithFrame:frame]; 
    if (self) [self initialize]; 
    return self; 
} 

- (void) initialize { 
    UIImage * backgroundImage = [[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"progress-bg" ofType:@"png"]] 
           resizableImageWithCapInsets:UIEdgeInsetsMake(0.0f, 10.0f, 0.0f, 10.0f)]; 

    UIImage * foregroundImage = [[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"progress-bg" ofType:@"png"]] 
           resizableImageWithCapInsets:UIEdgeInsetsMake(0.0f, 10.0f, 0.0f, 10.0f)]; 

    _backgroundImageView = [[UIImageView alloc] initWithFrame:self.bounds]; 
    _backgroundImageView.image = backgroundImage; 
    [self addSubview:_backgroundImageView]; 

    _foregroundImageView = [[UIImageView alloc] initWithFrame:self.bounds]; 
    _foregroundImageView.image = foregroundImage; 
    [self addSubview:_foregroundImageView]; 

    UIEdgeInsets insets = foregroundImage.capInsets; 
    minimumForegroundWidth = insets.left + insets.right; 

    availableWidth = self.bounds.size.width - minimumForegroundWidth; 

    [self adjustProgress:0.0f]; 
} 

나는 200x20 포인트로 인터페이스 빌더에 UIView을 생성 내가 사용하고이 사용자 정의 클래스 MCProgressBarView이 될 것을보기를 할당했다. 앱이 실행되면 initWithCoder이 실행되고 1000x1000 크기의 진행보기가 만들어지며 IB에서보기의 크기는 무시됩니다.

IB에 할당 된 적절한 크기로 initWithCoder를 실행하려면 어떻게해야합니까?

참고 : 저는 200x20으로 하드 와이어를 연결하고 싶지 않으며 런타임에이 코드를 설정하고 싶지 않습니다. 이 일을 할 수있는 방법이 있습니까?

답변

2

TL : DR : 프레임/경계 논리를 viewDidLayoutSubviews으로 옮깁니다.

initWithCoder:은 프레임 논리를 수행하는 데 안전하지 않습니다. 이를 위해서는 viewDidLayoutSubviews을 사용해야합니다. Apple은 iOS 10부터 1000x1000 범위를 사용합니다. 버그 또는 고의적 인 경우 명확하지 않지만 순 긍정적 결과가있는 것으로 보입니다. 사람들이 여기에 와서 물어 봅니다. ;-)

사실, initWithCoder:은 결코 그러한 논리에 대해 안전하지 않습니다. 과거에는 아이폰 5의 화면 경계가 IB로 사용 되었기 때문에 화면의 경계가 아이폰 6 플러스 크기 나 아이 패드 크기로 커지고 시각적 인 문제가 발생할 수있다.

이제 Apple에서는 경계를 1000x1000으로 설정하기 때문에 모든 경우에 맞지 않습니다. 뷰에 대한 레이아웃 패스가 수행되면 경계가 수정됩니다.

+1

UIView 기반 클래스에 viewDidLayoutSubviews가 없습니다. viewController를 사용하여 뷰 크기를 올바르게 설정하면이 모든 것이 Apple에서 ios에 대해 많은 상상을합니다. – SpaceDog

+0

@SpaceDog'layoutSubviews'를 사용하십시오. –

+0

확인. 클래스에'layoutSubviews'를 구현했습니다. 해당 메서드가 실행될 때 아무 것도하지 않고도 뷰가 올바른 크기로 표시되지만 응용 프로그램에 표시 될 때 1000x1000입니다. – SpaceDog