[iPhone] UITabBarController 이용시 UIViewController의 viewDidLoad가 호출되지 않는 문제 해결

UIViewController를 초기화 할때는 보통 다음과 같은 방식을 사용합니다.
[code]UIViewController *viewController = [[UIViewController alloc] init];[/code]
혹은 NIB를 이용한 다음과 같은 방법도 사용하게 됩니다.
[code]UIViewController *viewController = [[UIViewController alloc] initWithNibName:@”nibName” bundle:[NSBundle mainBundle]];[/code]
위와 같이 호출할 경우에는 자동으로 초기화가 되며 loadView, viewDidLoad가 순차적으로 호출되게 됩니다.

그런데 UITabBarController를 Interface Builder를 사용하여 다른 UIViewController를 등록하여 사용하게 되면 위의 두 메서드가 초기화시에 호출되지 않습니다.

또한 비슷한 컨트롤인 UINavigationController로 같은 문제를 가지고 있습니다. 이게 버그인지 무엇인지 잘 모르겠군요.

이런 난감한 문제를 해결하기 위해서 검색을 해보았지만 역시나 IB를 사용하지 않고 초기화 하는 방법밖에 없는 모양입니다.

[code]// UITabBarController 초기화
UITabBarController *tabBarController = [[UITabBarController alloc] init];
tabBarController.customizableViewControllers = nil;
 
// 3개의 다른 UIViewController 생성
// 3개의 뷰는 UINavigationView를 사용합니다.
UIViewController *View1 = [[UIViewController alloc] init];
UINavigationController *tab1Controller = [[UINavigationController alloc] initWithRootViewController:View1];
tab1Controller.tabBarItem.image = [UIImage imageNamed:@”1.png”];
[View1 release];
 
UIViewController *View2 = [[UIViewController alloc] init];
UINavigationController *tab2Controller = [[UINavigationController alloc] initWithRootViewController:View2];
tab2Controller.tabBarItem.image = [UIImage imageNamed:@”2.png”];
[View2 release];
 
UIViewController *View3 = [[UIViewController alloc] init];
UINavigationController *tab3Controller = [[UINavigationController alloc] initWithRootViewController:View3];
tab3Controller.tabBarItem.image = [UIImage imageNamed:@”3.png”];
[View3 release];
 
tabBarController.viewControllers = [NSArray arrayWithObjects: tab1Controller, tab2Controller, tab3Controller, nil];
 
[window addSubview: tabBarController.view];[/code]
위와 같은 방법을 사용하시면 정상적으로 작동하는 것을 알 수 있습니다.

참고  : http://discussions.apple.com/thread.jspa?threadID=1670615

[iPhone] UILabel 문자열 크기에 맞추어 frame 변경하기

iPhone 개발의 모든 컨트롤은 frame이라는 개념을 사용하여 뷰에 붙이게 됩니다.

이는 컨트롤이 붙을 위치와 차지할 크기를 가지고 있는 CGRect라는 이름의 구조체를 사용합니다.

UILabel을 사용할 경우에 보면 글자의 길이를 예측하기 힘든 경우가 많습니다. 하지만 뷰에 붙이기 전에 크기를 결정 지어야 하죠.

이 문제는 문자열의 크기에 맞추어 자동으로 frame이 맞추어 지면 해결되는 문제입니다. 다음과 같은 방법을 사용하시면 됩니다.

[code]#import <UIKit/UIStringDrawing.h>
 
NSString *labelText = @”Hello, Nice to meet you”;
CGSize labelSize = [labelText sizeWithFont:[UIFont systemFontOfSize:14.0f]];
UILabel label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 10.0f, labelSize.width, labelSize.height)];
label.text = labelText;
label.font = [UIFont systemFontOfSize:14.0f];
[self.view addSubView:label];
[label release];
 
NSLog(@”label size is %f, %f”,labelSize.width, labelSize.height);[/code]

찍히는 로그를 보시면 아시겠지만 labelText의 폰트와 글자 길이에 따라 labelSize의 값이 바뀌게 됩니다.

멀티라인을 이용할 경우는 [이곳]을 참고하세요.