I want to make my blue underline start and end within the red frame. So, I'm trying to get the X position, the starting position of my UIButton. The red one (red is a bg color). How can I do that?
Things I've tried:
promoButton.frame.origin.x
or
promoButton.bounds.origin.x
result: 0.0
promoButton.layer.position.x
This actually move the underline, but it started at the 'P' of 'Promo' instead of the red frame.
Can anyone tell me how to get the frame X position?
Thankyou in advance.
Update:
This is how i put it in the storyboard:
First there is this Tab View
Next, I have the container
Then the Promo button it self
I guess 0.0 is because it's inside a view. but is it possible to calculate X position from the screen tho?




You can do this with auto-layout / constraints, so you don't need to worry about "frames."
We'll setup the Storyboard like this - note: we are NOT adding the "underline view" in the Storyboard:
I've given the "container view" and the buttons different background colors to make it easier to see the framing.
We'll make
@IBOutletconnections to the three buttons:and we'll connect the
Touch Up Insidefor all buttons to the same function.In
viewDidLoad()we'll create and add theunderlineView, and give it aHeightconstraint of4.0. It looks like you want it about 8-points below the buttons, so we'll also give it aTopconstraint relative to the Bottom of the first button (doesn't really matter which button, as we're assuming they are the same).Now, we'll add two class properties:
Again in
viewDidLoad()we'll create those two constraints, and set them related tobtn1.When we tap a button, we'll:
deactivate those two constraints
re-make them related to the tapped button
and animate the change
@IBAction func btnTap(_ sender: UIButton) { // de-activate the underline view constraints underlineLeadingConstraint.isActive = false underlineWidthConstraint.isActive = false
}
Here's the complete controller class:
Here's how it looks when running:
Since we are now using constraints - instead of calculating frame coordinates - the underline width and position will automatically update when the "tab buttons" change... such as on device rotation.