简体   繁体   English

如果视图位于UIStackView内部,则中心点错误

[英]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. 我只是想获得UIButton的中心点,如果我点击它在其上绘制一些东西。 But the problem is that the center point is wrong. 但是问题是中心点是错误的。 My buttons are inside of a UIStackView . 我的按钮在UIStackView

What I am trying to do inside button action: 我想在按钮动作内做什么:

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

but it gives me wrong CGPoint() . 但这给了我错误的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 ? 所以我的问题是,如果视图位于UIStackView内部,应该如何获取它的中心?

You need to convert the UIButton frame to the superview. 您需要将UIButton框架转换为超级视图。 Checkout Apple docs 结帐Apple文档

What does "it gives me wrong CGPoint()" mean? “它给我错误的CGPoint()”是什么意思? 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: 如果要在视图控制器的内容视图的坐标系中居中,则需要使用一种UIView转换方法,例如:

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.) (请注意,上面的代码中不需要“ self”,而是添加了“ self”以清楚地表明view是视图控制器的内容视图。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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