UINavigationItem图像始终居中

时间:2017-07-16 19:22:26

标签: ios swift

我正在使用此代码在UINavigationItem中设置自定义图片:

let button = UIButton(type: .system)
button.frame = CGRect(origin: .zero, size: CGSize(width: 34, height: 34))
button.setImage(image, for: .normal)
button.addTarget(target, action: action, for: .touchUpInside)
leftBarButtonItem = UIBarButtonItem(customView: button)

效果如下所示:effect

来自同一设备但来自“照片”应用的对比屏幕截图如下所示:

photos

正如您所看到的,我的应用程序中的后退按钮会向中心移动一点点。

为什么我的图片与其他应用不一样?

1 个答案:

答案 0 :(得分:5)

尝试设置具有所需宽度的UIView,然后将UIButton作为子视图添加到该UIView,然后再分配给leftbarbuttonItem

    let button = UIButton(type: .system)
    button.frame = CGRect(x: -20, y: 0, width: 35, height: 35 )
    button.backgroundColor = UIColor.blue
    button.setImage(UIImage.init(named: "backButton"), for: .normal)

    let view = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 35)));
    view.addSubview(button);
    view.backgroundColor = UIColor.yellow

    let leftButton = UIBarButtonItem(customView: view)
    self.navigationItem.leftBarButtonItem = leftButton