先前有提過搜尋控制器 (Search Controller),現在想要讓搜尋控制器客制按鈕,預設只有一個取消按鈕,那我們怎麼讓它變成兩個按鈕呢?
查詢了一下,原來要透過非正規的方式,先找到searchDisplayController上的searchBar,再來遍歷searchBar上頭的UINavigationButton,於是我們就能變更「取消按鈕」的樣子。
可是要怎麼變成兩個、三個、多個按鈕呢?我很巧妙地生成另一個「確認按鈕」,它就放在取消按鈕之上,然後設定點擊它後要怎麼處理。
/** Theme: SearchDisplayController Button IDE: Xcode 7 Language: Objective C Date: 105/04/21 Author: HappyMan Blog: https://cg2010studio.wordpress.com/ */ -(void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller{ self.searchDisplayController.searchBar.showsCancelButton = YES; UIButton *cancelButton; UIView *topView = self.searchDisplayController.searchBar.subviews[0]; for (UIView *subView in topView.subviews) { if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) { cancelButton = (UIButton*)subView; } } if (cancelButton) { // Set the new title of the cancel button [cancelButton setTitle:@" 取消" forState:UIControlStateNormal]; UIButton *okButtonx = [UIButton buttonWithType:UIButtonTypeCustom]; okButtonx.frame = CGRectMake(0, 0, 60, 30); [okButtonx setTitle:@"確認" forState:UIControlStateNormal]; [cancelButton addSubview:okButtonx]; [okButtonx addTarget:self action:@selector(okButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; } }
於是我點擊確認按鈕,真的去執行我指定的功能!
話說,現在Xcode 7.2去使用UISearchDisplayController,已經會跳出警告訊息,說它已經在iOS 8開始被棄用了呢!所以未來就找更好的內建作法囉~因為是接前人的專案來改,所以姑且繼續用啦XD~
隨意留個言吧:)~