简体   繁体   中英

Wrong center point if view is inside UIStackView

I am simply trying to get UIButton 's center point if I tap it to draw something on it. But the problem is that the center point is wrong. My buttons are inside of a UIStackView .

What I am trying to do inside button action:

let myButtonCenter = contentView.convert(sender.center, from: stackView)

but it gives me wrong CGPoint() .

This is my view stack:

在此处输入图片说明

I also tried like this:

func getTappedButtonCenter(sender: UIButton) -> CGPoint{
        var buttonsArray = [UIButton]()
        for view in stackView.arrangedSubviews {
            let horizontalStackView = view as! UIStackView
            for view in horizontalStackView.arrangedSubviews {
                let button = view as! UIButton

                buttonsArray.append(button)

            }
        }

        let buttonIndex = buttonsArray.index(of: sender)

        let tappedButton = buttonsArray[buttonIndex!] as! UIButton

        return convert(tappedButton.center, from: tappedButton)

    }

So my question is, how should I get view's center if it is inside UIStackView ?

You need to convert the UIButton frame to the superview. Checkout Apple docs

What does "it gives me wrong CGPoint()" mean? A view's center is expressed in its superview's coordinate system. In this case, your buttons' superviews will be the stack view. If you want the center in the coordinate system fo your view controller's content view, you'll need to use one of the UIView conversion methods, like:

let temp = sender.center
let myButtonCenter = self.view.convert(temp, from: sender)

(Note that "self" is not needed in the code above, and is added to make it clear that view is the view controller's content view.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM