iOS 11 導航欄 item 偏移問題 和 Swift 下 UIButton 設置 title、image 顯示問題

 

iOS 11 導航欄 item 偏移問題 和 Swift 下 UIButton 設置 title、image 顯示問題

記錄兩個最近開發中遇到的兩個問題swift

  • iOS 11 下導航欄 item 會在 push 和 pop 的時候發生偏移問題
  • Swift 中 UIButton 設置了 image 和 title 後,title 沒法顯示問題

問題描述

iOS 11 中導航欄在使用過程當中 item 發生位置偏移,效果如圖:
markdown

 

問題分析

  1. iOS 10 以前沒有問題!
  2. 必須使用系統建立方式
  3. 兩邊 item 必須是使用一樣的建立方式

基類中:XYNavigationController中ide

  1. 統一建立返回按鈕,使用系統方法(從棧中的第二個VC開始)
  2. nav棧中首個VC,本身建立BackBtn(一樣用系統方法)

分類中:UIBarButtonItem (XYAdd)spa

  1. 提供快速建立方法的 leftItem
  2. 提供快速建立方法的 rightItem

解決問題

  • 導航欄基類中,重寫並攔截對應的 Push 方法
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    
    if (self.childViewControllers.count > 0) { //非rootViewController
        
        // 設置返回按鈕  【這裏必須用系統方法建立,使用自定義 View 設置 item 會發生偏移】
        //viewController.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithimage:[UIImage imageNamed:@"navigationButtonReturn"] selImage:[UIImage imageNamed:@"navigationButtonReturnClick"] target:self action:@selector(back)]; //返回
        
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationButtonReturn"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
        viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
        
        viewController.hidesBottomBarWhenPushed = YES;
        
    }
    
    [super pushViewController:viewController animated:animated];
}

- (void)back{
    [self popViewControllerAnimated:YES];
}
  • 可定義 UIBarButtonItem 分類,快速建立 item,內部在iOS 11 下不可再用自定義 View 的方式
+ (UIBarButtonItem *)xy_itemWithTarget:(id)target action:(SEL)action title:(NSString *)title{
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:target action:action];
    item.tintColor = [UIColor blackColor];
    
    return item;
}

Swift 中設置 title 和 不一樣狀態 image ,title沒法正常顯示

Swift 下同時設置了UIButton 的 title 和 image ,title沒法正確顯示。
這應該是 Swift 的一個bug,項目中若是須要此功能,正確的實現方式應該是設置 Button 的不一樣狀態下的背景圖code

optionBtn.setBackgroundImage(UIImage(named: "btn_image_normal"), for: .normal)
optionBtn.setBackgroundImage(UIImage(named: "btn_answer_highlighted"), for: .highlighted)

//optionBtn.setImage(UIImage(named: "btn_image_normal"), for: .normal)
//optionBtn.setImage(UIImage(named: "btn_answer_highlighted"), for: .highlighted)

optionBtn.setTitle("按我", for: .normal)
optionBtn.setTitle("按我", for: .highlighted)
  
optionBtn.setTitleColor(UIColor.black, for: .normal)
optionBtn.setTitleColor(UIColor.black, for: .highlighted)
相關文章
相關標籤/搜索