避免基于框架重叠视图

时间:2017-03-15 10:58:04

标签: ios objective-c swift xcode uiview

我有以下Graphview:

enter image description here

这是一个简单的UIView,它包含两种其他类型的UIViews:

  1. 顶点
  2. 顶点之间的边缘
  3. 我目前正在视图上随机“生成”顶点(代码跟随)并根据它们的中心点连接顶点:

    /// Layout our subviews
    override public func layoutSubviews() {
        nameLabel.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height * 0.1)
        self.backgroundColor = UIColor.white
        addSubview(nameLabel)
    
        print(self.graph.vertexCount)
    
        for index in 0 ..< self.graph.vertexCount{
            // Draw Vertexes
            let vertexName = self.graph.vertexAtIndex(index)
            let vertex:Vertex = Vertex(name: vertexName)
    
            let VALID_WIDTH = self.bounds.size.width - vertex.bounds.size.width
            let VALID_HEIGHT = self.bounds.size.height - vertex.bounds.size.height
    
            let x = CGFloat(CGFloat(arc4random()).truncatingRemainder(dividingBy: VALID_WIDTH))
            let y = CGFloat(CGFloat(arc4random()).truncatingRemainder(dividingBy: VALID_HEIGHT))
    
            vertex.frame = CGRect(x: x, y: y, width: vertex.frame.size.width, height: vertex.frame.size.height)
            self.addSubview(vertex)
            self.vertices.append(vertex)
        }
    
        // Draw Edges
        for vertexIndex in 0 ..< self.graph.vertexCount{
            let edges = self.graph.edgesForIndex(vertexIndex)
            for var edge:Edge in edges{
                let from:Vertex = vertices[edge.u]
                let to:Vertex = vertices[edge.v]
    
                let edgeView = EdgeView(frame: self.frame, from: from, to: to, edge: edge)
                self.addSubview(edgeView)
                self.edgesViews.append(edgeView)
            }
        }
    }
    

    我的问题是,有时(因为它随机产生)顶点和边缘可以相互重叠,例如:

    enter image description here

    有没有办法解决我的问题?

1 个答案:

答案 0 :(得分:0)

我现在使用了以下功能。基本上它需要一个随机的rect并对照包含CGRect的数组中的每个元素进行检查。如果任何元素相交,则会创建一个新的随机CGRect并再次尝试。

效果为O(n)

func getNewRectIfIntersect(rect:CGRect) -> CGRect {
    var newRect:CGRect = CGRect()

    var doesNotIntersect = false

    while doesNotIntersect == false {

        let x = CGFloat(CGFloat(arc4random()).truncatingRemainder(dividingBy: CGFloat(VALID_WIDTH)))
        let y = CGFloat(CGFloat(arc4random()).truncatingRemainder(dividingBy: CGFloat(VALID_HEIGHT)))

        newRect = CGRect(x: x, y: y, width: 50, height: 50)

        let matches = rectarray.filter { $0.intersects(newRect) }

        print("there were \(matches.count) matches")

        if matches.count == 0 {
            // do some things
            doesNotIntersect = true
        } else {
            doesNotIntersect = false
        }
    }


    return newRect
}