调整 UIBarButtonItem 的大小

Resize 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 作为应用栏

在这些情况下,我可以建议您做的事情和我通常做的事情是,您创建一个新图像,该图像是您想要的图像尺寸,并将该图像用于您的自定义 UIBarButtonItem。当你有大图像时,尺寸很棘手。

来自 iOS11 导航栏使用自动布局,因此您必须添加约束以调整 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了解详情