aircraft
aircraft

Reputation: 26896

Bounds.size.width is not the real width

I initialized two button in StoreTabView.swift:

@IBDesignable class StoreTabView: UIView

store_button = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: self.bounds.size.width / 2.0, height: self.bounds.size.height))

user_button = UIButton.init(frame: CGRect.init(x: self.bounds.size.width / 2.0, y: 0, width: self.bounds.size.width / 2.0, height: self.bounds.size.height))

And in my storyboard I set the view's class to StoreTabView, and set the constrains:

And I find the self.bounds.size.width is not the real width of it, in my simulator-5s, the logical resolution should be 320 rather than 375, but In Debug View Hierarchy, I found it is 375.

enter image description here

And in the console I print two button to show detail:

<UIButton: 0x7fd79be63620; frame = (187.5 0; 187.5 45); opaque = NO; layer = <CALayer: 0x60000023a9e0>>
Printing description of $7:
<UIButton: 0x7fd79be63360; frame = (0 0; 187.5 45); opaque = NO; layer = <CALayer: 0x60000023a8e0>>

We can see the width is 187.5, equals 375/2, so, self.bounds.size.width why is not 320 ? how to make the it to be 320 width? because the button's width should be 160 rather than 187.5.

Upvotes: 1

Views: 875

Answers (2)

Rakesh Gujari
Rakesh Gujari

Reputation: 161

Clear your basics -

The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).

The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.

Thank me later :)

Upvotes: 1

Adamsor
Adamsor

Reputation: 770

Why not use auto layout? In such matter it's easier to control and create views. If you are creating buttons from code I guess you're not using storyboard. Then constraint you are looking for looks like so.

buttonsSuperview.addConstraint(NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: buttonsSuperview, attribute: .width, multiplier: 0.5, constant: 1.0))

Of course you're gonna need more than this constraint (for height and position also).

If you are using storyboard it's really easy. You drag connection from button to it's superview, set equal widths and then just modify constraint's multiplier.

Upvotes: 0

Related Questions