ios - subview 中两个 CGPoint 之间的线 - 无法确定嵌套 subview 的框架

标签 ios swift uiview

我正在尝试在两个 CGPoint 之间画一条线,我附上图片以供引用。 View Hierarchy

我无法确定嵌套在 View 层次结构中的 subview 的框架。我尝试过使用:-

let framev1 = self.view.convertRect(subview.frame, fromView: self.containerView)

如何获得深深嵌套在 View 层次结构中的 subview 的精确坐标?

为了在两个 CGPoint 之间画线,我使用这个函数:

func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) {

    //design the path
    let path = UIBezierPath()
    path.moveToPoint(start)
    path.addLineToPoint(end)

    //design path in layer
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.CGPath
    shapeLayer.strokeColor = lineColor.CGColor
    shapeLayer.lineWidth = 2.0

    view.layer.addSublayer(shapeLayer)
}

//我打算如何调用上面的函数来为我画一条线。 显然这不起作用,它在 UIViewController.view 的 (0,0) 处绘制线 a

func viewDidLoad() {
    super.viewDidLoad()

  drawLineFromPoint(CGPointMake(subview1.frame.minX,subview1.frame.midY),  toPoint:CGPointMake(subview2.frame.maxX,subview2.frame.midY ), ofColor: UIColor.redColor().colorWithAlphaComponent(1), inView: self.view)                  
}

最佳答案

对于你的第一个问题,尝试使用这个函数:

func convertRectCorrectly(rect: CGRect, toView view: UIView) -> CGRect {
    if UIScreen.mainScreen().scale == 1 {
        return self.convertRect(rect, toView: view)
    }
    else if self == view {
        return rect
    }
    else {
        var rectInParent = self.convertRect(rect, toView: self.superview)
        rectInParent.origin.x /= UIScreen.mainScreen().scale
        rectInParent.origin.y /= UIScreen.mainScreen().scale
        let superViewRect = self.superview!.convertRectCorrectly(self.superview!.frame, toView: view)
        rectInParent.origin.x += superViewRect.origin.x
        rectInParent.origin.y += superViewRect.origin.y
        return rectInParent
    }
}

示例:

let framev1 = self.view.convertRectCorrectly(subview.frame, toView: self.containerView)

它应该返回父容器 View 中的 subview 坐标。

关于ios - subview 中两个 CGPoint 之间的线 - 无法确定嵌套 subview 的框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37874673/

相关文章:

ios - CLViewController,全屏显示细节 View ,iOS sdk

ios - "Unable to download App... could not be installed at this time"- adobe Phonegap 构建 ios

ios - 当 UIView 高度设置为零时, View 的子控件不隐藏

ios - 容器 View Controller 委托(delegate)分配

iphone - iOS 框架无法创建对象

ios - 图像未按正确顺序附加

swift - 我创建了一个自定义 UIView,其中我尝试使用 UISwitch 来打开和关闭 blackStroke 边框

ios - 添加到容器后不调用按钮

ios - 'CIImage is undeclared type' 奇怪的错误

ios - 带有左右栏项目的中心导航栏标题?