一個最基本的動態ToolBar的設定,並使用兩個Button來做移除及設定動態ToolBar的顯示
Xcode版本4.5 & IOS6
1. 開啓一個新的專案
2. 設定StoryBoard並加入一個Label及兩個Button
3. 設定dynamicToolBarViewController.h
@property (weak, nonatomic) IBOutlet UILabel *showLabel;
@property (weak, nonatomic) IBOutlet UIButton *showButton;
@property (weak, nonatomic) IBOutlet UIButton *delButton;
@property (nonatomic) UIToolbar *myToolBar;
@property (nonatomic) UIBarButtonItem *myBarItem1;
@property (nonatomic) UIBarButtonItem *myBarItem2;
@property (nonatomic) UIBarButtonItem *myBarItem3;
@property (nonatomic) UIBarButtonItem *myBarItem4;
@property (nonatomic) UIBarButtonItem *myBarItem5;
-(void)showText1 ;
-(void)showText2 ;
-(void)showText3 ;
4. 將控制碼加入到設定dynamicToolBarViewController. m
#import "dynamicToolBarViewController.h"
@interface dynamicToolBarViewController ()
@end
@implementation dynamicToolBarViewController
@synthesize showLabel;
@synthesize myToolBar;
@synthesize myBarItem1, myBarItem2, myBarItem3, myBarItem4, myBarItem5;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)showToolBar:(id)sender {
[self setupMyToolBar];
[self.view addSubview:myToolBar];
}
- (IBAction)delToolBar:(id)sender {
[self removeAllSubView];
}
-(void)setupMyToolBar
{
myToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 704, 1024, 44.0)];
//myBarItem1= [[UIBarButtonItem alloc] initWithCustomView:label];
myBarItem1= [[UIBarButtonItem alloc]initWithTitle:@"Test1" style:UIBarButtonItemStylePlain target:self action:@selector(showText1)];
myBarItem2= [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemFixedSpace) target:nil action:nil];
myBarItem3= [[UIBarButtonItem alloc]initWithTitle:@"Test2" style:UIBarButtonItemStyleBordered target:self action:@selector(showText2)];
myBarItem4= [[UIBarButtonItem alloc]initWithBarButtonSystemItem:(UIBarButtonSystemItemFlexibleSpace) target:nil action:nil];
myBarItem5= [[UIBarButtonItem alloc]initWithTitle:@"Test3" style:UIBarButtonItemStyleDone target:self action:@selector(showText3)];
myBarItem2.width = 420;
NSArray *toolbarItems = [[NSArray alloc] initWithObjects:myBarItem1,myBarItem2,myBarItem3,myBarItem4,myBarItem5,nil];
myToolBar.items = toolbarItems;
}
- (void) removeAllSubView
{
for(UIView *subview in [self.view subviews]) {
if([subview isKindOfClass:[UIToolbar class]]) {
[subview removeFromSuperview];
}
}
}
-(void)showText1
{
NSString *text = @"測試一";
showLabel.text = text;
}
-(void)showText2
{
NSString *text = @"測試二";
showLabel.text = text;
}
-(void)showText3
{
NSString *text = @"測試三";
showLabel.text = text;
}
@end
5. 顯示結果如圖









沒有留言:
張貼留言