为什么自定义导航栏按钮图像拉伸?
我试图添加一个导航栏按钮与自定义图像。但是,无论我使用什么方法,图像总是显得很紧张。为什么自定义导航栏按钮图像拉伸?
方法1:
let barbuttonitem = UIBarButtonItem(image: UIImage(named: "apps_small"), style: .plain, target: self, action: nil)
navigationItem.leftBarButtonItem = barbuttonitem
看起来像这样:
方法2:
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "apps_small"), for: .normal)
button.addTarget(self, action: #selector(TeachingRootViewController.appsTouched), for: .touchUpInside)
button.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
button.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
似乎升IKE在此:
方法3:
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "apps_small"), for: .normal)
button.setTitle("Button", for: .normal)
button.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
button.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
button.imageEdgeInsets = .init(top: 5, left: 5, bottom: 5, right: 300)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
navigationItem.leftBarButtonItem?.imageInsets = .init(top: 5, left: 5, bottom: 5, right: 300)
它看起来像这样:
正如你可以看到标题已经一去不复返了。
UI层次结构,它看起来像这样:
看来,按钮已采取了所有的空格在导航栏中。
但是,对于按钮没有问题的系统项目:
是否有任何人谁知道这个问题的原因是什么?我想我已经用完了想法。
尝试将其添加为一个子视图,而不是将其设置为leftBarButtonItem
var leftButton = UIButton(frame:CGRect(x: 0, y: 0, width: 10, height: 10))
var background = UIImageView(image: UIImage(named: "apps_small"))
background.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
leftButton.addSubview(background)
self.navigationController.navigationBar.addSubview(leftButton)
感谢您的回复!然而,它不会编译...编译器抱怨“类型'UINavigationItem'的值没有成员'addSubview'”。 UIBarButtonItem也没有'addSubview'。 – imxieyi
我没有创建一个UIBarButtonItem ..生病编辑这个使用navController ..所以你可以再试一次 –
@imxieyi你可以再试一次UIButton和UINavigationBar作为我提供的代码吗? –
你解决这个问题的? –