调整UIBarButtonItem的大小

时间:2018-02-12 05:57:44

标签: swift uibarbuttonitem

我的徽标图片是1024x1024和obvs。我需要在导航栏中调整大小以使其有意义。 对于iOS 11和10我都找到了解决方案,但是既没有工作也没有解决原因!

    var reportButton: UIButton
    reportButton = UIButton.init(type: .custom)
    let reportButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    reportButton.imageView?.contentMode = .scaleToFill
    reportButton.setImage(UIImage.init(named: "1024Icon.png"), for: UIControlState.normal)

    if #available(iOS 11.0, *) {
        // Running iOS 11 OR NEWER
        reportButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    } else {
        reportButton.frame = CGRect.init(x: 0, y: 0, width: 23, height: 30)
        reportButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
    }
    let rtyButton = UIBarButtonItem(customView: reportButton)
    appBar.navigationBar.leftBarButtonItems = [rtyButton]

仅供参考我使用MDCAppBar作为应用栏

2 个答案:

答案 0 :(得分:1)

我建议您做什么以及在这些情况下我通常做的是您为图像创建所需尺寸的新图像,然后将该图像用于自定义UIBarButtonItem。当你有大图像时,这些尺寸很棘手。

答案 1 :(得分:0)

在iOS 11中,导航栏使用自动布局,因此您必须添加约束以调整UIImageButton的大小,例如,如果要在右侧添加30x30的UIBarButtonItem:

override func viewDidLoad() {
    let btn = UIButton(type: .custom);
    btn.setImage(UIImage(named: "your_image.png"), for: .normal);

    btn.frame = CGRect(x: 0, y: 0, width: 30, height: 30);
    btn.addTarget(self, action: #selector(your_method(_:)), for: .touchUpInside);
    let item = UIBarButtonItem(customView: btn);
    self.navigationItem.setRightBarButtonItems([item], animated: false);    

    item.customView?.widthAnchor.constraint(equalToConstant: 30).isActive = true;
    item.customView?.heightAnchor.constraint(equalToConstant: 30).isActive = true;
}

有关详情,请参见此link