获取 Swift 坐标 (x,y) 处的 UILabel 值
Get value of UILabel at coordinate (x,y) in Swift
我正在寻找一种在给定 (x,y) 坐标处查找 UILabel 的值(文本)的方法。
所有其他问题似乎都是关于获取标签的 (x,y),我正在尝试做相反的事情...
例如 (30,40) 将 return 该位置的标签值。
谢谢!
更新
func getLabel(location: CGPoint){
let view = self.view.hitTest(location, withEvent:nil)
//I would like to get the value of the label here but I'm not sure how to.
}
@IBAction func tap(sender: UITapGestureRecognizer) {
var coordinate = sender.locationInView(GraphView?())
getLabel(coordinate)
}
您可以通过 hit-testing 完成此操作。
将您想要的点传递给顶级视图,它将return包含该点的视图层次结构中最深的视图。
UIView *view = [self.view hitTest:location withEvent:nil];
在Swift中,它看起来像
let selectedView = view.hitTest(location, withEvent: nil)
更新:
您需要将标签的 userInteractionEnabled
设置为 true,您的标签才能注册命中。
您需要检查 returned 视图以查看它是否是标签,然后检查它是否有任何文本。
if let label = selectedView as? UILabel
{
if label.text!
{
// .. do what you want with the label's text
}
}
我正在寻找一种在给定 (x,y) 坐标处查找 UILabel 的值(文本)的方法。
所有其他问题似乎都是关于获取标签的 (x,y),我正在尝试做相反的事情...
例如 (30,40) 将 return 该位置的标签值。
谢谢!
更新
func getLabel(location: CGPoint){
let view = self.view.hitTest(location, withEvent:nil)
//I would like to get the value of the label here but I'm not sure how to.
}
@IBAction func tap(sender: UITapGestureRecognizer) {
var coordinate = sender.locationInView(GraphView?())
getLabel(coordinate)
}
您可以通过 hit-testing 完成此操作。
将您想要的点传递给顶级视图,它将return包含该点的视图层次结构中最深的视图。
UIView *view = [self.view hitTest:location withEvent:nil];
在Swift中,它看起来像
let selectedView = view.hitTest(location, withEvent: nil)
更新:
您需要将标签的 userInteractionEnabled
设置为 true,您的标签才能注册命中。
您需要检查 returned 视图以查看它是否是标签,然后检查它是否有任何文本。
if let label = selectedView as? UILabel
{
if label.text!
{
// .. do what you want with the label's text
}
}