在ToolBar上添加SegmentedControl
2010-08-13 20:45 Tracy E 阅读(844) 评论(0) 编辑 收藏 举报学习iphone这么长时间,还没怎么用过ToolBar,今天项目需求,要用到它。本以为很容易用,结果发现想在ToolBar上添加一个segmentedControl就把我难住了一下下。
ToolBar上所有的Items都必须是UIBarButtonItem类型的,因此需要先把SegmentedControl转变成UIBarButtonItem才能加上去。
toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 372, 320, 44)]; UIBarButtonItem *todayItem = [[UIBarButtonItem alloc] initWithTitle:@"今日" style:UIBarButtonItemStyleBordered target:self action:@selector(backToToday)]; UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; segmentedControl = [[UISegmentedControl alloc] initWithItems: [NSArray arrayWithObjects:@"日",@"周",@"月",nil]]; [segmentedControl setFrame:CGRectMake(0, 0, 150, 30)]; [segmentedControl setSegmentedControlStyle:UISegmentedControlStyleBar]; segmentedControl.selectedSegmentIndex = 0; [segmentedControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged]; UIBarButtonItem *segmentItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl]; [segmentedControl release]; NSArray *array = [[NSArray alloc] initWithObjects:todayItem,spaceItem, segmentItem,spaceItem,nil]; [todayItem release]; [spaceItem release]; [segmentItem release]; [toolBar setItems:array]; [array release]; [self.view addSubview:toolBar];