2009-04-20 69 views
11

在我的應用程序我有一個工具欄,並在某一點我想禁用或啓用一些按鈕。最簡單的方法是什麼?我怎樣才能訪問UIToolbar的項目屬性?UIToolBar - 禁用按鈕

這裏是我的代碼:

-(void)addToolbar { 
    NSMutableArray *buttons = [[NSMutableArray alloc] init]; 

    //Define space 
    UIBarButtonItem *flexibleSpaceItem; 
    flexibleSpaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:nil action:NULL]; 

    //Add "new" button 
    UIBarButtonItem *newButton = [[UIBarButtonItem alloc] 
            initWithTitle:@"New" style:UIBarButtonItemStyleBordered target:self action:@selector(new_clicked)]; 
    [buttons addObject:newButton]; 
    [newButton release]; 

    //Add space 
    [buttons addObject:flexibleSpaceItem]; 

    //Add "make active" button 
    UIBarButtonItem *activeButton = [[UIBarButtonItem alloc] 
            initWithTitle:@"Make Active" style:UIBarButtonItemStyleBordered target:self action:@selector(make_active_clicked)]; 
    [buttons addObject:activeButton]; 
    [activeButton release]; 

    [buttons addObject:flexibleSpaceItem]; 

    //Add "edit" button 
    UIBarButtonItem *editButton = [[UIBarButtonItem alloc] 
            initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(edit_clicked)]; 
    [buttons addObject:editButton]; 
    [editButton release]; 

    [flexibleSpaceItem release]; 

    [toolBar setItems:buttons]; 
    [buttons release]; 
} 

預先感謝您。

回答

14

最簡單的方法是將對UIBarButtonItem的引用保存爲實例變量。

# header file 
UIBarButtonItem *editButton; 

然後你的代碼變得

# .m file 
editButton = [[UIBarButtonItem alloc] 
       initWithTitle:@"Edit" 
       style:UIBarButtonItemStyleBordered 
       target:self 
       action:@selector(edit_clicked)]; 
[buttons addObject:editbutton]; 

現在,在任何實例方法在任何地方,禁用按鈕一樣簡單:

editButton.enabled = NO; 

也立即不release它,因爲這個班的學生擁有按鈕對象。所以release它在dealloc方法代替。

+0

您還可以禁用工具欄上的用戶交互(userInteractionEnbaled = NO) – jjxtra 2013-11-22 01:59:43

6

Fast enumeration來救援!

- (void) setToolbarButtonsEnabled:(BOOL)enabled 
{ 
    for (UIBarButtonItem *item in self.toolbarItems) 
    { 
     item.enabled = !enabled; 
    } 
}