我一直试图改变UIBarButton - >在iOS11中使用UIBarButton的contentEdgeInsets将UIButton设置为-20。但没有任何作用。我也试图添加灵活的空间,但它仍然无法正常工作。以下是我的代码
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
}
检查此图像我想要的内容。
答案 0 :(得分:0)
你必须这样使用:
btn1.leftAnchor.constraint(equalTo: btn1.leftAnchor, constant: -20).isActive = true
let item1 = UIBarButtonItem(customView: btn1)
self.navigationItem.leftBarButtonItems = [item1]
答案 1 :(得分:0)
我在挖掘了几个小时后得到了我的解决方案,解决方案非常简单。 放一个额外的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]