解決iOS11導航欄自定義左按鈕偏移及按鈕圖片橫向拉伸的問題

iOS 11之前自定義導航欄的左按鈕代碼如下

//    UIButton *toRootVC = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [toRootVC setImage:[UIImage imageNamed:@"首頁_u82"] forState:UIControlStateNormal];
    //    [toRootVC setFrame:CGRectMake(0, 0, 50, 50)];
    //    [toRootVC addTarget:self action:@selector(toRootVCButton:) forControlEvents:UIControlEventTouchUpInside];
    //    UIBarButtonItem *leftHelpItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
//設置一個寬度為負的item與按鈕一同加入
    //    leftHelpItem.width = -15;
    //    self.navigationItem.leftBarButtonItems = @[leftHelpItem ,[[UIBarButtonItem alloc] initWithCustomView:toRootVC]];

但是在iOS 11中這樣的設置無效了
經過一番折騰:修改代碼如下

    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 60, 60)];
    UIButton *leftbtn =[UIButton buttonWithType:UIButtonTypeCustom];
    leftbtn.frame = CGRectMake(-15, -5, 55, 55);
    [leftbtn setImage:[UIImage imageNamed:@"首頁_u82"] forState:UIControlStateNormal];
    [leftbtn addTarget:self action:@selector(toRootVCButton:) forControlEvents:UIControlEventTouchUpInside];
    [leftView addSubview:leftbtn];
    [self.view addSubview:leftView];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftView];

以上代碼解決了按鈕顯示上的問題,但是仍存在響應范圍較以前版本偏小的問題,歡迎交流和指正。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。