使用Xcode ver 9.3,Swift开发iOS应用程序。
导航左栏按钮不会出现。你能告诉我如何显示左栏按钮吗?
当我尝试使用相同代码的右侧按钮时,它显示没有任何问题。
代码和故事板如下。
第一个TableView代码
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let naviButton = UIBarButtonItem(title: "naviButton", style: UIBarButtonItemStyle.plain, target: self, action: #selector(Tapped))
// Left bar button does not appear
self.navigationItem.leftBarButtonItem = naviButton
// Right bar button do appear
self.navigationItem.rightBarButtonItem = naviButton
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
@objc func Tapped() {
print("Tapped")
}
...
故事板
模拟器
答案 0 :(得分:2)
您不能在
UINavigationBar
中两次放置相同的按钮。因此,创建2个单独的按钮,然后将其分配给leftbarButton
和rightbarButton
:
override func viewDidLoad() {
super.viewDidLoad()
let leftNaviButton = UIBarButtonItem(title: "lNaviButton", style: UIBarButtonItemStyle.plain, target: self, action: #selector(Tapped1))
self.navigationItem.leftBarButtonItem = leftNaviButton
let rightNaviButton = UIBarButtonItem(title: "rNaviButton", style: UIBarButtonItemStyle.plain, target: self, action: #selector(Tapped2))
self.navigationItem.rightBarButtonItem = rightNaviButton
}
@objc func Tapped1() {
print("Tapped1")
}
@objc func Tapped2() {
print("Tapped2")
}
答案 1 :(得分:2)
您无法将两次相同的视图添加到UI。如果您创建单个UIBarButtonItem
,则可以将其添加为左侧或右侧导航项,但不能同时添加。如果你想在两边都有物品,那么只需创建另一个:
override func viewDidLoad() {
super.viewDidLoad()
let leftNaviButton = UIBarButtonItem(title: "naviButton", style: UIBarButtonItemStyle.plain, target: self, action: #selector(Tapped))
// Left bar button does not appear
self.navigationItem.leftBarButtonItem = leftNaviButton
let rightNaviButton = UIBarButtonItem(title: "naviButton", style: UIBarButtonItemStyle.plain, target: self, action: #selector(Tapped))
// Right bar button do appear
self.navigationItem.rightBarButtonItem = rightNaviButton
}
答案 2 :(得分:2)
正如我在评论中建议的那样,您的问题与您为UIBarButtonItem
和self.navigationItem.rightBarButtonItem
设置相同self.navigationItem.leftBarButtonItem
的事实有关,您需要创建两个UIBarButtonItem
并指定一个用于右边,另一个用于左边,我想你知道怎么做;)
答案 3 :(得分:0)
您可以为UIButton创建一个扩展名,如
extension UIButton {
class func addBarButton(tittle:String,_ target: Any, action: Selector) -> UIBarButtonItem{
let button = UIButton(type: .system)
button.setTitle(tittle, for: .normal)
button.addTarget(target, action: action, for: .touchUpInside)
return UIBarButtonItem(customView: button)
}
}
和你的主控制器只需要写下面的代码
self.navigationItem.rightBarButtonItem = UIButton.addBarButton(tittle: "RNaviButton", self, action: #selector(Tapped1))
self.navigationItem.leftBarButtonItem = UIButton.addBarButton(tittle: "LNaviButton", self, action: #selector(Tapped2))
按钮的和动作方法
@objc func Tapped1() {
print("Tapped1")
}
@objc func Tapped2() {
print("Tapped2")
}
如果你想对两个按钮都采取相同的动作,你也可以在两个按钮动作中传递相同的动作。