Swift得到当前元素的Y坐标

时间:2015-06-02 16:02:35

标签: swift position coordinates popover

我有一些UILabel可以按下来打开菜单。按下时,它们将标签本身作为参数调用我的函数。我制作一个在手机视图中表现正常的弹出框,但我想在ipad视图上定位它。

我的问题是我无法获得被按下的UILabel的确切位置。

我试过

myYCoordinates = label.bounds.origin.y

myYCoordinates = label.frame.origin.y

optionMenu.popoverPresentationController?.sourceRect = CGRectMake(self.view.bounds.size.width / 2, myYCoordinates, 1.0, 1.0)

但我无法获得良好的坐标。

我不知道是不是因为我的标签在2视图的桌面视图中,或者根本没有办法。

提前感谢您的帮助。

这是我的观点(对发展机密性的裁剪) enter image description here 这是我按标签时附加的内容 enter image description here 这就是我想要的样子 enter image description here

我试过了 optionMenu.popoverPresentationController?.sourceRect = label.frame

enter image description here

2 个答案:

答案 0 :(得分:2)

根据@ÖzgürErzil的回答,我发现我可以简单地使用

optionMenu.popoverPresentationController?.sourceView = label
optionMenu.popoverPresentationController?.sourceRect = CGRectMake(label.frame.width, label.frame.height / 2, 1.0, 1.0)

通过将源视图设置为我的标签并使用标签宽度和高度来定位它。

感谢

答案 1 :(得分:-1)

如果您动态创建UILabel,请在设置时尝试设置位置:  CGRectMake(x,y,width,height)

var label = UILabel(frame: CGRectMake(0, 0, 200, 20))

或者如果它在storyBoard中,则必须使用约束方法并使用autolayout。解释here