본문 바로가기

프로그램 경험/iOS

[iPhone] 코드로 UIToolbar에 UISegmentedControl 넣기

툴바에 세그먼트 컨트롤을 삽입하는데 IB에서는 그냥 드래그 해서 잘만 되더만 코드로는 어떻게 하는지 잘 모르겠더라... 아래와 같이 하면 되더라~^^ self는 UIToolbar 상속 받은 클래스다.
#define TOOLBARBUTTON(TITLE, STYLE, SELECTOR) 	[[[UIBarButtonItem alloc] initWithTitle:TITLE style:STYLE target:self action:SELECTOR] autorelease]

	NSMutableArray *tbitems = [NSMutableArray array];
	
	[tbitems addObject:TOOLBARBUTTON(@"아이템1", UIBarButtonItemStyleBordered, @selector(action))];
	[tbitems addObject:TOOLBARBUTTON(@"아이템2", UIBarButtonItemStyleBordered, @selector(action))];
	UIBarButtonItem *bbi = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil] autorelease];
	bbi.width = 350.0f;
	[tbitems addObject:TOOLBARBUTTON(@"아이템3", UIBarButtonItemStyleBordered, @selector(action))];
	
	self.items = tbitems;
	
	NSArray *buttonNames = [NSArray arrayWithObjects:@"세그1", @"세그2", nil];
	UISegmentedControl* segmentedControl = [[UISegmentedControl alloc] initWithItems:buttonNames];
	
	segmentedControl.frame = CGRectMake(250.0f, 8.0f, 120.0f, 30.0f);
	segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 
	segmentedControl.selectedSegmentIndex = 0;
	[segmentedControl setWidth:70 forSegmentAtIndex:0];
	[segmentedControl setWidth:90 forSegmentAtIndex:1];
	[segmentedControl setTintColor:[UIColor darkGrayColor]];
	
	[self addSubview:segmentedControl];
	[segmentedControl release];