自定义的 UIBarButtonItem

有时候由于项目的需要我们需要自定义UIBarButtonItem,但是自定义的rightBarButtonItem 和leftBarButtonItem距离屏幕的距离往往不是我们想要的,下面是我在项目中的解决办法。

自定义的 UIBarButtonItem

 collectionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
 [collectionBtn setImage:[UIImage imageNamed:@"collect"] forState:UIControlStateNormal];
 [collectionBtn setImage:[UIImage imageNamed:@"collect_focus"] forState:UIControlStateSelected];
 [collectionBtn addTarget:self action:@selector(collectionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
 collectionBtn.frame = CGRectMake(0, 0, 50, 50);
 UIBarButtonItem *collectionView = [[UIBarButtonItem alloc]initWithCustomView:collectionBtn];
 UIBarButtonItem *rightPlaceHolderItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
//通过width指定宽度
 rightPlaceHolderItem.width = -15;
//placeHolder只有在数组的左边有效
 self.navigationItem.rightBarButtonItems = @[rightPlaceHolderItem,collectionView];
  • 以上是rightBarButtonItem,leftBarButtonItem和这类似
  • UIBarButtonSystemItem的类型常量中,UIBarButtonSystemItemFlexibleSpace ,UIBarButtonSystemItem不是按钮,它们是用来调整按钮间距用的对象,能设置指定宽度的BarButton

你可能感兴趣的:(自定义的 UIBarButtonItem)