문제

라벨을 중앙에있는 가장 좋은 방법은 무엇입니까? UIView? 당신이 다음과 같은 일을한다면

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(view.frame.origin.x / 2, view.frame.origin.y / 2, 50.0, 50.0)];

그런 다음 레이블의 원점을보기의 중심으로 설정합니다. 가장 좋은 방법은 중앙 속성을 사용하여 시야의 중심을 해당 지점으로 설정하는 것입니다. 그래서 다음 코드를 사용해 보았습니다.

UIView *aView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
aView.backgroundColor = [UIColor darkGrayColor];
CGRect frame = aView.frame;

UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 125.0f, 30.0f)];
[aLabel setCenter:CGPointMake(frame.origin.x / 2, frame.origin.y / 2)];

그것은 왼쪽 상단의 뷰의 범위를 바깥에있는 레이블을 산출합니다.

도움이 되었습니까?

해결책

당신이 잘못하고있는 가장 중요한 것은 절반을 차지하는 것입니다. 기원 절반이 아닌 가치 크기

그러나이 경우이를 계산할 필요도 없습니다. 다음과 같은 작업을 수행하십시오.


UIView *aView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
aView.backgroundColor = [UIColor darkGrayColor];

UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 125, 30)];
aLabel.center = aView.center;

(참고, 해당 좌표를 플로트로 강제 할 필요는 없습니다.이 경우 ints를 더 읽기 쉬운 것처럼 보이게합니다).

또한 스타일의 문제이지만 이미 속성 구문을 사용하고 있기 때문에 (aView.backgroundColor) 중앙 속성에도 사용할 수도 있습니다 :-)

다른 팁

부모의 수평 중앙에있는 아동을 배치하려면 그렇게 위치를 계산합니다.

childX = (parentWidth - childWidth) / 2

(이것은 높이에도 적용됩니다).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top