2017-08-30 166 views
0

我正在學習如何使用Swift,並且我意識到我無法直接將工具欄添加到具有UITableViewController的故事板中,所以我努力嘗試以編程方式添加它。以編程方式構建工具欄

這就是我想使它看起來像:

iOS screenshot

現在,我添加以下代碼:

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) 

它看起來是這樣的:

iOS screenshot

但我找不到方法使其看起來與原稿的間距相同,而且如果我設置圖像,我沒有找到適合尺寸的方法,因爲我需要它。

我試過使用這個代碼,我發現這裏似乎工作,但是當我加載我的應用程序,它只是顯示沒有任何元素的酒吧。

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

你究竟想要達到什麼目的?一個視圖內的標籤欄?或整個應用程序的標籤欄?如果是前者,那麼我推薦一個關於git hub的好項目https://github.com/kitasuke/PagingMenuController – TNguyen

+0

首先,你想添加一個'UITabBar'嗎?或者'UIToolBar'? – DonMag

回答

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」太被甩在空間的左側添加靈活的空間。

+0

需要「外部」靈活空間:'let arr:[Any] = [flexibleSpace1,homeButton,flexibleSpace2,addButton,flexibleSpace3,loveButton,flexibleSpace4]' – DonMag

+0

@DonMag:正確。我會更新答案。多謝,夥計。 – Amit

+0

@DonMag:我不認爲'flexibleSpace4'是必需的。 – Amit

相關問題