2016-09-11 5 views
1

UIView에 범주를 만들어 프로그래밍 방식으로 위치를 지정하고 내보기의 크기를 쉽게 조정할 수 있습니다. 주어진 뷰를 수평 또는 수직으로 가운데에 맞출 방법을 만들고 싶습니다. superview. 그래서 나는 다음과 같은 일을 할 수수퍼 뷰 내에보기를 중앙에 놓으려고 시도합니다.

카테고리

- (void)centerHorizontally { 
    self.center = CGPointMake(self.window.superview.center.x, self.center.y); 
} 

- (void)centerVertically { 
    self.center = CGPointMake(self.center.x, self.window.superview.center.y); 
} 

사용하지만

UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)]; 
[v centerHorizontally]; 

,이 작동하지 않는 것 같습니다. 내 솔루션에 대한 잘못된 점은 무엇입니까?

+0

@SathiReddy이 - 하나 개 불필요한 태그를 추가하여 간단하게 질문을 편집 불필요하게 중지하십시오. 편집은 유용하고 완전해야합니다. 태그를 추가하지 마십시오. 질문에 문제가있는 부분을 모두 수정하십시오. 또는이 경우 아무것도하지 마십시오. 대부분의 태그 편집 제안은 불필요합니다. – rmaddy

답변

2

뷰를 중앙에 배치하기 전에 뷰를 부모 뷰에 추가해야합니다.

UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)]; 
[someOtherView addSubview:v]; 
[v centerHorizontally]; 

귀하의 카테고리가 잘못되었습니다. 창문이 개입하지 마라. 당신은 슈퍼 뷰의 크기에 기초해야합니다

- (void)centerHorizontally { 
    self.center = CGPointMake(self.superview.bounds.size.width/2.0, self.center.y); 
    // or 
    self.center = CGPointMake(CGRectGetMidX(self.superview.bounds), self.center.y); 
} 

- (void)centerVertically { 
    self.center = CGPointMake(self.center.x, self.superview.bounds.size.height/2.0); 
    // or 
    self.center = CGPointMake(self.center.x, CGRectGetMidY(self.superview.bounds)); 
} 
+0

나는'bounds.size.width'와'bounds.size.height'을 의미한다고 생각하지만 고마워요! – Apollo

+0

예, 수정되었습니다. 감사. – rmaddy

관련 문제