自动布局应用于 UIButton 时如何移动 UIBarButton?

How to move UIBarButton when auto layout applied to UIButton?

我一直在尝试使用 iOS11 中 UIBarButton 的 contentEdgeInsets 将 UIBarButton -> UIButton 移动到 -20。但没有任何效果。我也尝试添加 flexible space 但它仍然无法正常工作。下面是我的代码

    let btn1 = UIButton(type: .custom)
    let imageString = UserDefaults.standard.object(forKey: "UserImage") as! String
    let imageURl = URL(string: imageString)
    btn1.sd_setBackgroundImage(with: imageURl, for: .normal, placeholderImage: UIImage(named: "profilePlaceHolder.png"))
    btn1.imageView?.contentMode = .scaleAspectFit
    btn1.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
    btn1.applyNavBarConstraints(size: (width: 30, height: 30))
    //btn1.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0)
    btn1.layer.cornerRadius = 15
    btn1.layer.borderColor = UIColor.appColorPurple.cgColor
    btn1.layer.borderWidth = 1
    btn1.layer.masksToBounds = true
    btn1.addTarget(self, action: #selector(BaseViewController.showProfile), for: .touchUpInside)
    let item1 = UIBarButtonItem(customView: btn1)
    self.navigationItem.leftBarButtonItems = [item1]

    func applyNavBarConstraints(size: (width: CGFloat, height: CGFloat)) {
        let widthConstraint = self.widthAnchor.constraint(equalToConstant: size.width)
        let heightConstraint = self.heightAnchor.constraint(equalToConstant: size.height)
        heightConstraint.isActive = true
        widthConstraint.isActive = true
    }

检查这张图片是我想要的。

你必须这样使用:

btn1.leftAnchor.constraint(equalTo: btn1.leftAnchor, constant: -20).isActive = true
let item1 = UIBarButtonItem(customView: btn1)
self.navigationItem.leftBarButtonItems = [item1]

我在挖掘几个小时后得到了解决方案,解决方案非常简单。 放一个额外的 UIView 然后在里面放 UIButton.

        let bgView = UIView()
        bgView.backgroundColor = UIColor.clear
        bgView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)


        let btn1 = UIButton(type: .custom)
        btn1.frame = CGRect(x: -10, y: 0, width: 34, height: 34)
        btn1.addTarget(self, action: #selector(BaseViewController.showProfile), for: .touchUpInside)
        btn1.imageView?.contentMode = .scaleAspectFit
        let imageString = UserDefaults.standard.object(forKey: "UserImage") as! String
        let imageURl = URL(string: imageString)
        btn1.sd_setImage(with: imageURl, for: .normal, placeholderImage: UIImage(named: "profilePlaceHolder.png"))
        btn1.layer.cornerRadius = 17
        btn1.layer.borderColor = UIColor.appColorPurple.cgColor
        btn1.layer.borderWidth = 1
        btn1.clipsToBounds = true
        bgView.addSubview(btn1)

        let item1 = UIBarButtonItem(customView: bgView)
        self.navigationItem.leftBarButtonItems = [item1]