Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make 2 toolbar/footer buttons with 50% width with Swift/Storyboard

I'm trying to display a title bar, image, and then two buttons almost like below. The main differences are that I want to two item buttons to be 50% width and each a solid color (taking up the entire bottom of the screen). I'm not using a tab bar because the buttons are just to change the image out, not the entire view controller.

screenshot

So far using the storyboard, I'm just stuck on the buttons. I have them in a toolbar as bar button items. I then tried to set their width's in the controller:

@IBOutlet weak var firstButton: UIBarButtonItem!
@IBOutlet weak var secondButton: UIBarButtonItem!

override func viewDidLoad() {
    super.viewDidLoad()
    self.firstButton.width = self.view.bounds.width / 2
    self.secondButton.width = self.view.bounds.width / 2
}

screenshot

I believe they're being set properly, but the toolbar is forcing some space to be in front of the first button. I haven't even made it to changing their background colors yet, but I'm hoping that will be simple once I finish the spacing.

I'm pretty new to iOS development, so any tips are appreciated. I'm aiming for having it work universally but I'd settle for getting it working on iPhone locked portrait.

like image 387
Tom Prats Avatar asked May 06 '15 01:05

Tom Prats


3 Answers

Using Autolayout is relative easy, You need to set the width of the button equals to the SuperView and set the Multiplier constant to 0.5

Or set the Toolbar width equals to Superview with Multiplier 1.0 and then the UIButtons equals the toolbar's width but with Multiplier 0.5

Something like this

like image 51
Vincent Avatar answered Nov 08 '22 12:11

Vincent


Previous answers didn't solve the problem, it looks like there's some internal padding with using a toolbar. That and you might not be able to add constraints to Bar Buttons.

My actual solution is:

Remove Bar Buttons and Toolbar. Add two UIButtons to the bottom. Add the following constraints

First Button

  • Leading Space to Superview

Second Button

  • Leading Space to Superview

First Botton and Second Button

  • Bottom Space to Superview
  • Proportional Width to ImageView with a 0.5 multiplier
like image 3
Tom Prats Avatar answered Nov 08 '22 14:11

Tom Prats


If you're using auto layout, you need to set your toolbar's width equal to the container view with a width constraints. Then set width of two items equal to each other, set those spacings to zero.

There's no need to set their width manually.

BTW, do not forget to do the same thing to your UIImageView if you want it to be full width.

Helpful links:

http://www.raywenderlich.com/83129/beginning-auto-layout-tutorial-swift-part-1 http://www.raywenderlich.com/50317/beginning-auto-layout-tutorial-in-ios-7-part-1 http://www.raywenderlich.com/64392/video-tutorial-beginning-auto-layout

like image 1
Allen Hsu Avatar answered Nov 08 '22 12:11

Allen Hsu