[英]iPhone - Add “Add” Button when Edit button is selected in UITableView
我的應用程序中有一個表視圖,顯示了一些項目。 當我點擊一個項目時,會出現一個新的表格視圖(帶有導航控制器:推送)。 因此,在Table視圖的頂部,現在有一個帶有自動“后退”箭頭的導航控制器可以返回。 我在右側啟用了“編輯”按鈕。
現在我想要當我點擊編輯按鈕時,后退按鈕應該消失,並且應該有一個“+”添加按鈕而不是后退按鈕。 這可能嗎? 或者可以同時在屏幕上顯示“編輯”和“添加”按鈕?
謝謝
這很容易。 覆蓋視圖控制器的setEditing:animated:
方法。 切換編輯/完成按鈕時會調用此方法(假設您使用的是UIViewController
的標准editButtonItem
)。
在此方法中,您可以創建一個“添加”按鈕,並將其設置為左側的按鈕項。 這將隱藏后退按鈕。 刪除“添加”按鈕,后退按鈕將重新出現。
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
if (editing) {
// Add the + button
UIBarButtonItem *addBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addAction:)];
self.navigationItem.leftBarButtonItem = addBtn;
} else {
// remove the + button
self.navigationItem.leftBarButtonItem = nil;
}
}
是的,這是我使用的方法:
為后退按鈕和添加按鈕都有一個屬性,並在viewDidLoad中設置它:
self.backButton = self.navigationItem.leftBarButtonItem;
self.addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addPressed:)];
現在,您只需交換按鈕並在按下“編輯”時相應地更新TableView狀態。 在這里,我還將“編輯”按鈕更改為“完成”:
- (IBAction)editBarButtonPressed:(UIBarButtonItem *)sender {
if (self.tableView.editing == NO) {
UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(editBarButtonPressed:)];
self.navigationItem.rightBarButtonItem = myButton;
[self.tableView setEditing:YES animated:YES];
[self.navigationItem setLeftBarButtonItem:self.addButton animated:YES];
} else {
UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editBarButtonPressed:)];
self.navigationItem.rightBarButtonItem = myButton;
[self.tableView setEditing:NO animated:YES];
[self.navigationItem setLeftBarButtonItem:self.backButton animated:NO];
}
}
希望這能回答你的問題。 :) br denrase
后退箭頭按鈕是導航控制器按鈕。 因此,如果您想要消失相同的按鈕,那么您必須在下面編寫以下代碼: -
self.navigationItem.hidesBackButton=YES;
現在,如果您想在導航控制器上添加自定義按鈕,請使用以下代碼: -
UIBarButtonItem *customButton =
[[UIBarButtonItem alloc]
initWithTitle:@"Add"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(yourMethod:)];
self.navigationItem.rightBarButtonItem = customButton;
您可以在表視圖開始編輯時以編程方式隱藏后退按鈕,然后在導航欄的左側添加“添加”按鈕。
[self.navigationItem setHidesBackButton:YES];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addButtonPressed)];
[self.navigationItem setLeftBarButtonItem:addButton];
然后,當用戶按下完成時,用“后退”按鈕替換“添加”按鈕:
[self.navigationItem setHidesBackButton:NO];
self.navigationItem.leftBarButtonItem = self.navigationItem.backBarButtonItem;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.