我正在学习如何使用Swift,并且我意识到我无法将工具栏直接添加到带有UITableViewController
的故事板中,所以我很难尝试以编程方式添加它。
这就是我想让它看起来像:
现在,我添加了这段代码:
let homeButton = UIBarButtonItem(title: "H", style: .plain, target: self, action: #selector(ProfileButtonTapped))
let addButton = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(ProfileButtonTapped))
let loveButton = UIBarButtonItem(title: "Love", style: .plain, target: self, action: #selector(ProfileButtonTapped))
let arr: [Any] = [homeButton, addButton, loveButton]
setToolbarItems(arr as? [UIBarButtonItem] ?? [UIBarButtonItem](), animated: true)
super.viewDidAppear(animated)
它看起来像这样:
但是我找不到一种方法让它看起来与原版的间距相同,而且如果我设置图像,我找不到根据需要调整尺寸的方法。
我尝试使用此处找到的代码并且似乎有效,但是当我加载我的应用时,它只显示没有任何元素的条形码。
navigationController?.setToolbarHidden(false, animated: true)
let homeButn = UIImage(named: "HomeButton")
let zeroPoint = CGPoint.zero
let settingsButton = UIButton(type: UIButtonType.custom) as UIButton
settingsButton.frame = CGRect(origin: zeroPoint, size: CGSize(width: 27, height: 27))
settingsButton.setImage(homeButn, for: [])
settingsButton.addTarget(self, action: #selector(ProfileButtonTapped), for: UIControlEvents.touchUpInside)
let rightBarButtonItem = UIBarButtonItem(customView: settingsButton)
navigationItem.setRightBarButton(rightBarButtonItem, animated: true)
我真的不知道如何做到这一点,任何想法?非常感谢!
答案 0 :(得分:1)
如果有帮助的话,试试这个:
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
let homeButton = UIBarButtonItem(title: "H", style: .plain, target: self, action: #selector(ProfileButtonTapped))
let flexibleSpace1 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
let addButton = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(ProfileButtonTapped))
let flexibleSpace2 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
let loveButton = UIBarButtonItem(title: "Love", style: .plain, target: self, action: #selector(ProfileButtonTapped))
let arr: [Any] = [flexibleSpace, homeButton, flexibleSpace1, addButton, flexibleSpace2, loveButton]
setToolbarItems(arr as? [UIBarButtonItem] ?? [UIBarButtonItem](), animated: true)
super.viewDidAppear(animated)
您也可以在“H”的左侧添加灵活空间以获得左侧空间。