我有两个 UIImageView 数组,其中填充了 18 个 block 和圆
var myBlocks = [UIImageView]()
var myCircles = [UIImageView]()
因此,在我以漂亮的方式将我的圆圈添加到屏幕上,然后我的 block 覆盖在它们之上之后,我调用一个函数来设置圆圈和 block 的标签以匹配(如果颜色匹配)。意思是如果 block 是鲜红色的,我想找到鲜红色的圆圈,并将它们都标记为 0,依此类推。下面我设置标签的这一行抛出错误:
Cannot subscript a value of type '[UIImageView]' with an index of type 'UIImageView'
func setTags() {
for x in myBlocks {
for y in myCircles {
if x.tintColor == y.tintColor {
myBlocks[x].tag = y //Error here
}
}
}
}
有没有更简单的方法来做到这一点?我在创建时没有标记两者的原因是因为圆圈是使用打乱的数组创建的,因为我不希望在游戏加载时相同颜色的圆圈和相同颜色 block 彼此重叠。
编辑:我将其更改为 x.tag = y.tag 并且看起来更好。但是,当我点击其中一个方 block 时,我现在正在打印两份。
let objectDragging = recognizer.view?.tag
print(objectDragging)
//and
print("the tag of the object your touching is \(myBlocks[objectDragging!])")
我在使用过程中得到的日志是
Optional(13)
the tag of the object your touching is <UIImageView: 0x7f8d4ba103a0;
frame = (263 180; 100 100); opaque = NO; tintColor =
UIExtendedSRGBColorSpace 0.8 0.3 0.3 1; tag = 11; gestureRecognizers = <NSArray: 0x60000005fec0>; layer = <CALayer: 0x600000220580>>
所以有人说这个 block 被标记为 13,有人说是 11。13 是我打印出 myBlocks[count].tag 时所说的,我只是不知道 11 是从哪里来的myBlocks[objectDragging] 语句。
编辑 2:可能是因为 (myBlocks[objectDragging!]) 引用了不同的 block ?
最佳答案
你有两个问题。首先,myBlocks[x]
会引发错误,因为您正在遍历元素,而不是索引。其次,x.tag = y
引发错误,因为属性 tag is an Int并且您正在尝试分配一个 UIImageView
。
for x in myBlocks {
for y in myCircles {
if x.tintColor == y.tintColor {
x.tag = y.tag //fix here
}
}
}
编辑:或者,如果您想遍历索引:
for x in 0..<myBlocks.count {
for y in 0..<myCircles.count {
if myBlocks[x].tintColor == myCircles[y].tintColor {
myBlocks[x].tag = myCircles[y].tag
}
}
}
最后,如果你想要索引和元素,你可以这样做:
for (x, block) in myBlocks.enumerated() {
for (y, circle) in myCircles.enumerated() {
if block.tintColor == circle.tintColor {
myBlocks[x].tag = myCircles[y].tag
}
}
}
关于ios - 用标签按颜色匹配两个图像数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263668/