前提: leftBarButtonItem無法通過frame的x設(shè)置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, 如果設(shè)置成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]];