[英]Merge overlapping CGRects
If I have a class Button
:如果我有一个类
Button
:
class Button: Hashable {
private let id: String
var name: String
var rect: CGRect
}
I also have an array of Button
: var buttons: [Button]
, how would I merge every overlapping button in the buttons
array?我还有一个
Button
数组: var buttons: [Button]
,我将如何合并buttons
数组中的每个重叠按钮? CGRect
has an intersects() -> Bool
and union() -> CGRect
functions. CGRect
有一个intersects() -> Bool
和union() -> CGRect
函数。
I tried this and was getting index out of range errors:我尝试了这个并且正在获取索引超出范围的错误:
for i in 0..<buttons.count {
for j in (i+1)..<buttons.count {
if buttons[i].rect.intersects(buttons[j].rect) {
let secondRect = buttons[j].rect
let union = buttons[i].rect.union(secondRect)
buttons[i].rect = union
buttons.remove(at: j)
}
}
}
Swift for
loop is static, which means that range of the index determined at the start. Swift
for
循环是静态的,这意味着索引的范围在开始时确定。 While buttons.count
keeps decreasing when you remove a next item, both i
and j
are counting til the start buttons.count
, that's why you get a crash.当您删除下一个项目时,
buttons.count
会不断减少,但i
和j
都在计数直到开始buttons.count
,这就是您崩溃的原因。
There's no dynamic for
in swift (c-like), that's why you have to use while instead:有没有动态
for
斯威夫特(C类),这就是为什么你必须同时改为使用方法:
var i = 0
while i < buttons.count {
var j = i + 1
while j < buttons.count {
if buttons[i].rect.intersects(buttons[j].rect) {
let secondRect = buttons[j].rect
let union = buttons[i].rect.union(secondRect)
buttons[i].rect = union
buttons.remove(at: j)
} else {
j += 1
}
}
i += 1
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.