在 iOS 10 的開發實踐中,總有一些反覆出現的小問題讓人頭疼。本文整理了 8 個高頻場景及其解決方案,涵蓋搜索框、導航欄、列表優化等方方面面,希望能幫你少走彎路。
有時我們需要在代碼中主動觸發搜索框的「取消」按鈕。可以通過遍歷搜索欄視圖層級找到取消按鈕,並借助通知中心來響應其點擊事件:
#pragma mark UISearchDisplayDelegate
-(void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller {
for (UIView *view in controller.searchBar.subviews) {
for (UIView *subView in view.subviews) {
// 獲取「取消」按鈕
if ([subView isKindOfClass:[UIButton class]]) {
UIButton *cancelButton = (UIButton *)subView;
// 獲取點擊「取消」按鈕的響應事件
self.cancelSearchSELString = [[cancelButton actionsForTarget:controller.searchBar forControlEvent:UIControlEventTouchUpInside] objectAtIndex:0];
// 響應通知,執行方法
[[NSNotificationCenter defaultCenter] addObserver:controller.searchBar selector:NSSelectorFromString(self.cancelSearchSELString) name:@"cancelSearch" object:nil];
}
}
}
}
#pragma mark UISearchBarDelegate —— 點擊搜索按鈕
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
// 點擊按鈕時,發布取消搜索狀態通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"cancelSearch" object:nil];
// 發布—響應—取消通知
[[NSNotificationCenter defaultCenter] removeObserver:searchBar name:@"cancelSearch" object:nil];
}
借助 isMovingFromParentViewController 可以在 viewWillDisappear 中判斷當前 VC 是被 pop 還是被 push 覆蓋:
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self isMovingFromParentViewController]) {
NSLog(@"View controller was popped");
} else {
NSLog(@"New view controller was pushed");
}
}
if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
// iOS 7 及以上
[self.navigationController.navigationBar setBarTintColor:[UIColor yellowColor]];
} else {
// iOS 7 以下
[self.navigationController.navigationBar setTintColor:[UIColor yellowColor]];
}
[self.navigationController.navigationBar setTitleTextAttributes:@{
NSForegroundColorAttributeName: [UIColor redColor],
NSFontAttributeName: [UIFont fontWithName:@"mplus-1c-regular" size:21]
}];
只需一行就能消除列表底部多餘的空白單元格:
tableView.tableFooterView = [UIView new];
在設置 footer 間距時,返回 CGFLOAT_MIN 比寫死 1.0f 更為得體:
// footer 間距
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return CGFLOAT_MIN;
}
直接設置為 0 是無效的,最小只能到 1.0f。可以通過同時實現高度與視圖方法來徹底消除多餘間距:
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if (section == 0) {
return 6.0;
}
return 1.0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 5.0;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
return [[UIView alloc] initWithFrame:CGRectZero];
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
return [[UIView alloc] initWithFrame:CGRectZero];
}
UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:14.0f]; // iOS 8.2 開始支持 [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
以上就是 iOS 10 開發中經常遇到的 8 個典型問題及其解法。它們看似瑣碎,卻能在實際項目中切切實實地提升開發效率與用戶體驗,建議收藏以備隨時查閱。