RightBarButtonItem不显示在正确的位置
问题描述:
我编程方式创建一个UINavigationController和我的ViewController添加到它:RightBarButtonItem不显示在正确的位置
// wrap in a navigation controller
let navigationController = UINavigationController(rootViewController: myViewController)
self.present(navigationController, animated: true, completion: nil)
然后将图像添加到导航项目:
let backButton: UIBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: target, action: selector)
backButton.image = UIImage(named: "ic_back")
self.navigationItem.rightBarButtonItem = backButton
但我BarButton没有显示在正确的位置。我究竟做错了什么?
答
您需要初始化UIBarButton直接的UIImage或自定义视图:
即
雨燕3.0:
let image = UIImage(named: "ic_back")?.withRenderingMode(.alwaysOriginal)
let button = UIBarButtonItem(image: image, style: .plain, target: target, action: selector)
self.navigationItem.rightBarButtonItem = button
这将解决您的问题。
答
alloc和初始化UIButton
与期望的帧!将图像设置为该按钮。如果需要,设置内容模式!在此按钮上添加目标以处理点击!然后alloc and init
UIBarButtonItem
使用initWithCustomView
方法并通过UIButton
作为您创建的参数。
然后将navigationItem的rightBarbuttonItem设置为这个barbutton!
答
let btn1 = UIButton(type: .custom)
btn1.setImage(UIImage(named: "imagename"), for: .normal)
btn1.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
btn1.addTarget(self, action: #selector(Class.Methodname), for: .touchUpInside)
let item1 = UIBarButtonItem(customView: btn1)
self.navigationItem.setRightBarButtonItems(item1, animated: true)
答
您可以设置这样的导航栏上的按钮..
let Button = UIButton(frame: CGRect(x: 0, y: 0, width: 35, height: 40))
Button.setBackgroundImage(UIImage(named: "btn.png"), for: .normal)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: Button)
因此,这段代码可以帮助你实现你的查询
答
使用下面的代码添加边框到您的返回按钮,让我们知道如果它工作。
backButton.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
您可以更改宽度和高度acc。满足您的需求。
这也可能是一些图像问题。请检查其他图像。如果它适用于其他图像,肯定是使用的图像有问题 –
Mqke确保条形图像中的x和y坐标为零 –