Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the height and width of a button in iOS app using Swift 4.0 which is developed using Swift 3.0

Tags:

ios

swift4

xcode9

I am completely new to iOS development and I am supposed to fix some bugs in an iOS app which is made using Swift 3.0 and Xcode 8 and it works almost fine. But when I open it with Xcode 9 and Swift 4.0 it shows some buttons way different that they were before.

Here is the source code for one of those buttons.

let button: UIButton = UIButton.init(type: UIButtonType.custom)
    //set image for button
    button.setImage(UIImage(named: "menu.png"), for: UIControlState())
    button.frame = CGRect(x: 0, y: 0, width: 30, height: 23)
    let barButton = UIBarButtonItem(customView: button)
    button.addTarget(self, action: #selector(ViewController.shareButtonPressed), for: UIControlEvents.touchUpInside)

    self.navigationItem.leftBarButtonItem = barButton

this code is inside the ViewDidLoad method. My problem is when I remove,

button.setImage(UIImage(named: "menu.png"), for: UIControlState())

it disappears the button but when I change the height and the width from,

button.frame = CGRect(x: 0, y: 0, width: 30, height: 23)

it changes nothing. My problem is how can I fix this bug. Any suggestion, answer is highly appreciated and if the given details are not enough, please mention. Thank you!

like image 546
Sami Udakara Avatar asked Oct 19 '17 03:10

Sami Udakara


People also ask

How do I change the size of a button in Swift?

3. How To Change Swift Button Size & Position. To change button size and position, you should first open the Xcode Size Inspector pane by click View —> Inspectors —> Show Size Inspector menu item at Xcode top menu bar.

How do I change the width and height of an image in Swift?

Show activity on this post. extension UIImage { func imageResize (sizeChange:CGSize)-> UIImage{ let hasAlpha = true let scale: CGFloat = 0.0 // Use scale factor of main screen UIGraphicsBeginImageContextWithOptions(sizeChange, ! hasAlpha, scale) self. draw(in: CGRect(origin: CGPoint.


2 Answers

Beginning with iOS 11, views added to toolbars using UIBarButtonItem using UIBarButtonItem(customView:) are now laid out using auto layout. You should add sizing constraints on your button. For example:

button.widthAnchor.constraintEqualToConstant(30.0).isActive = true
button.heightAnchor.constraintEqualToConstant(23.0).isActive = true

Otherwise, auto layout will use the intrinsic content size of your header view which is likely not what you expect.

For more information see the WWDC 2017 session Updating your app for iOS 11.

like image 148
beyowulf Avatar answered Sep 19 '22 22:09

beyowulf


swift 4:

button.widthAnchor.constraint(equalToConstant: 30.0).isActive = true
button.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
like image 44
Chetan Dobariya Avatar answered Sep 23 '22 22:09

Chetan Dobariya