gpt4 book ai didi

ios - 避免基于框架的重叠 View

转载 作者:行者123 更新时间:2023-11-30 12:36:26 25 4
gpt4 key购买 nike

我有以下 Graphview:

enter image description here

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

  1. 顶点
  2. 顶点之间的边

我目前正在 View 上随机“生成”顶点(代码如下)并根据顶点连接顶点:

/// 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

有办法解决我的问题吗?

最佳答案

我现在使用了以下功能。基本上,它需要一个随机矩形,并根据包含 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
}

关于ios - 避免基于框架的重叠 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42807789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com