leftBarButtonItem 自定義UIView 向左偏移(非UIButton)

前提: leftBarButtonItem無法通過frame的x設置item的位置

目的:讓UINavigationBar的左邊,右邊item 自定義偏移(下面以leftBarButtonItem為例)
  • 一般leftBarButtonItem用UIButton自定義 都會出現(xiàn)圖片過右的情況,我們想按鈕內(nèi)容(文字,圖片)做偏移
  • leftBarButtonItem用UIButton自定義 可通過UIButton中的contentEdgeInsets屬性,去實現(xiàn)按鈕內(nèi)容偏移
  • 或者通過UIButton中的contentHorizontalAlignment屬性實現(xiàn)按鈕內(nèi)容的偏移
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"返回" forState:UIControlStateNormal];
        button.size = CGSizeMake(70, 30);

        // 讓按鈕內(nèi)部的所有內(nèi)容左對齊
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        // 讓按鈕的內(nèi)容往左邊偏移10
        button.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        
        // 修改導航欄左邊的item
        navVC.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
  • leftBarButtonItem中的CustomView, 如果設置成UIView, 則就沒有contentEdgeInsets和contentHorizontalAlignment屬性去修改的位置
  • 面對這種情況,蘋果給我們提供了UIBarButtonSystemItemFixedSpace這種item類型來處理.自定義View位置偏移
UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target:nil action:nil];  
negativeSpacer.width = -15;  //偏移距離  -向左偏移, +向右偏移
self.navigationItem.leftBarButtonItems = @[negativeSpacer, [[UIBarButtonItem alloc] initWithCustomView:button]];  
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容