閱讀642 返回首頁    go 技術社區[雲棲]


iOS導航BarButtonItem文字或者圖片與屏幕邊界的間隔調整方法

在設置navigationItem的leftBarButtonItem或rightBarButtonItem時,

用CustomView初始化UIBarButtonItem,不論怎麼設置CustomView的frame,

添加到導航條上之後總是和屏幕邊界有一定的間距(5pix),

如何自由調整這個間距呢?


下麵介紹兩種方法:

1、不用直接設置rightBartButtonItem而是設置rightBartButtonItems,並且第一個item設置為一個占位。

- (UIButton *)addRightItemWithTitle:(NSString *)title action:(SEL)action {
  UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  CGSize size = [title sizeWithFont:[UIFont systemFontOfSize:16]];
  
  //! 這裏需要根據內容大小來調整寬度
  button.frame = CGRectMake(0, 0, size.width <= 10 ? 70 : size.width + 10, 44);
  button.titleLabel.textColor = [UIColor whiteColor];
  button.titleLabel.font = [UIFont systemFontOfSize:16];
  button.titleLabel.textAlignment = NSTextAlignmentRight;
  [button setTitle:title forState:UIControlStateNormal];
  /**
   *  width為負數時,相當於btn向右移動width數值個像素,由於按鈕本身和邊界間距為5pix,所以width設為-15時,間距正好調整
   *  為10;width為正數時,正好相反,相當於往左移動width數值個像素
   */
  UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                     initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                     target:nil action:nil];
  negativeSpacer.width = -15;
  
  [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
  UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:button];
  self.navigationItem.rightBarButtonItems = @[negativeSpacer, backItem];
  return button;
}

2、如果是隻有圖片,那麼通過設置

[button setImageEdgeInsets:UIEdgeInsetsMake(0, -15, 0, -15)];這樣也可以調整

- (UIButton *)addRightItemWithImage:(NSString *)imageName action:(SEL)action {
  UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
  UIImage *image = [UIImage imageNamed:imageName];
  button.frame = CGRectMake(0, 0, image.size.width, image.size.height);
  
  // 這裏需要注意:由於是想讓圖片右移,所以left需要設置為正,right需要設置為負。正在是相反的。
  // 讓按鈕圖片右移15
  [button setImageEdgeInsets:UIEdgeInsetsMake(0, 15, 0, -15)];
  
  [button setImage:image forState:UIControlStateNormal];
  [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
  button.titleLabel.font = [UIFont systemFontOfSize:16];
  UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:button];
  self.navigationItem.rightBarButtonItem = rightItem;
  return button;
}


最後更新:2017-04-03 12:56:27

  上一篇:go 一勝九敗
  下一篇:go 淺談C#中new、override、virtual關鍵字的區別