我正在以编程方式创建一个UINavigationController并将我的ViewController添加到它:
// 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没有显示在正确的位置。我做错了什么?
答案 0 :(得分:3)
您需要将UIBarButton直接初始化为UIImage或自定义视图:
即,
Swift 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
这将解决您的问题。
答案 1 :(得分:1)
使用所需的帧分配和初始化UIButton
!将图像设置为该按钮。如果需要,设置内容模式!在此按钮上添加目标以处理点击!然后使用alloc and init
方法UIBarButtonItem
initWithCustomView
并将UIButton
作为您创建的参数传递。
然后将navigationItem的rightBarbuttonItem设置为此barbutton!
答案 2 :(得分:0)
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)
答案 3 :(得分:0)
您可以像这样在导航栏上设置按钮..
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)
因此,此代码可帮助您实现查询
答案 4 :(得分:-1)
使用以下代码将框架添加到backButton,并告诉我们它是否有效。
backButton.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
您可以更改宽度和高度acc。根据你的需要。