如何在UINavigationBar中更改UIBarButtonItem之间的空间?

时间:2015-08-04 07:34:55

标签: ios swift uinavigationbar

现在的样子:

enter image description here

这是它在Debug视图Hierarchy中的表示方式:

enter image description here

以下是我在代码中设置的方式:

func setupUserAndCartButtons() {

    var rightBarButtonItems = [UIBarButtonItem]()

    let cartBarButtonItem = UIBarButtonItem(image: DBCart.sharedCart().icon, style: .Plain, target: self, action: Selector("cartButtonTapped:"))

    rightBarButtonItems.append(cartBarButtonItem)

    let userIcon = UIImage(named: "icon-user")
    let userBarButtonItem = UIBarButtonItem(image: userIcon, style: .Plain, target: self, action: Selector("userButtonTapped:"))
    rightBarButtonItems.append(userBarButtonItem)

    navigationItem.rightBarButtonItems = rightBarButtonItems
}

热销可以让他们彼此靠近而不使用自定义视图吗?

4 个答案:

答案 0 :(得分:2)

使用UIBarButtonItem的imageInsets属性

在Objective-C [addContact setImageInsets:UIEdgeInsetsMake(0, -10,0, 0)];

答案 1 :(得分:0)

使用自定义视图添加按钮:

  //MARK:Customize Navigation Bar
  func addButtonsToNavigationBar(){
    let cartButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton

    cartButton.frame = CGRectMake(0,0,20,20)
    cartButton.addTarget(self, action: "cartButtonTapped:", forControlEvents: .TouchUpInside)
    cartButton.setImage(UIImage(named: DBCart.sharedCart().icon), forState: .Normal)

    let cartBarButtonItem = UIBarButtonItem(customView: cartButton)

    let userButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
    userButton.frame = CGRectMake(0,0,20,20)
    userButton.addTarget(self, action: "userButtonTapped:", forControlEvents: .TouchUpInside)
    userButton.setImage(UIImage(named: "icon-user"), forState: .Normal)

    let userBarButtonItem = UIBarButtonItem(customView: userButton)

    self.navigationItem.rightBarButtonItems=[cartBarButtonItem,userBarButtonItem]
  }

答案 2 :(得分:0)

UIBarButtonSystemItemFixedSpace用于调整导航栏项的间距。

示例代码:

- (void)setRightBarButtonItems {

    UIBarButtonItem *addTaskButton =
    [[UIBarButtonItem alloc] bk_initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                    handler:handler];

    UIBarButtonItem *negativeSeperator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];

    if ([UIDevice isIOS7Plus]) {
        negativeSeperator.width = -12;
    } else {
        negativeSeperator.width = -8;
    }
    UIBarButtonItem *separator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    separator.width = 50;

    [self.navigationItem setRightBarButtonItems:@[addTaskButton, separator, [self filterButton]]];
}

答案 3 :(得分:0)

Swift 4.1

 buttonName.imageInsets = UIEdgeInsetsMake(0, 30, 0, 0)

这会将按钮的右侧移至其他按钮。 希望这会帮助某人