2020-09-30

Swift -How to get the center frame of a button's titleLabel and not the button itself

I have a custom segmented control with 4 segments with a button in each segment. I had to make a change to the button's contentEdgeInsets:

// eg of the second button
customSegmentedControl.secondButton?.contentEdgeInsets = UIEdgeInsets(top: 0, left: -35, bottom: 0, right: 0)

The slider originally slid to each segment using button.frame.midX. After changing the contentEdgeInsets when the slider slides to a segment it looks as if it's in the wrong position because the title is no longer in the center of the button. I tried to change the slider to slide to the center of the button's button.titleLabel: button.titleLabel!.frame.midX but a weird bug occurs where the slider slides incorrectly.

for button in buttons {
            
    UIView.animate(withDuration: 0.2, animations: {

        self.slider.frame.origin.x = button.titleLabel!.frame.midX // button.frame.midX was what was originally used
         // if it's the selected button break ...
    })
}

How can I get the slider to slide to the center of the button's titleLabel? For example I want it to slide to the middle of the word Pencil which is the title of the button with its contentEdgeInsets changed and not the button itself.

enter image description here

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/2HIcPi5
https://ift.tt/33eO5X6

No comments:

Post a Comment