gpt4 book ai didi

swift - UIImageView 的 If 语句

转载 作者:行者123 更新时间:2023-11-30 13:48:17 25 4
gpt4 key购买 nike

我创建了一个 UIImagesViews 数组,并编写了一个代码来为它们分配随机图片。如果超过或 5 张图片显示相同的图片,我想制作一个 if 语句。

var images: [UIImageView] = [Image1, Image2, Image3, Image4, Image5, Image6, Image7, Image8, Image9]

不同的图片被命名为card1、card2、card3

let firstRandomNumber = arc4random_uniform(3) + 1
let firstRandomString:String = String(format: "card%i", firstRandomNumber)

self.Image1.image = UIImage(named: firstRandomString)

let secondRandomNumber = arc4random_uniform(3) + 1
let secondRandomString:String = String(format: "card%i", secondRandomNumber)

self.Image2.image = UIImage(named: secondRandomString)

所有图像都有自己的特定代码,如上面的代码。现在,正如我所说,如果五个或更多图像显示相同的图片,我想制作一个 if 语句或 switch-case。

编辑:这是更新后的代码;

let imageNames:NSArray = [firstRandomString, secondRandomString, thirdRandomString, fourthRandomString, fifthRandomString, sixthRandomString, seventhRandomString, eighthRandomString, ninthRandomString]

let maxRepeating = imageNames
.map {img in imageNames.reduce(0) { $1 == img ? $0 + 1 : $0} }
.reduce(0){ $1 > $0 ? $1 : $0 }

代码只有一个错误 .map {img in imageNames.reduce(0) { $1 == img ? $0 + 1 : $0} } 说;

Binary operator '==' cannot be applied to two 'Element' (aka 'AnyObject') operands

编辑:这是我从克里斯托弗·凯文那里尝试过的另一个代码;

var correct = 0

func checkImageDuplication() {
let imageArray : NSArray = [firstRandomString, secondRandomString, thirdRandomString, fourthRandomString, fifthRandomString, sixthRandomString, seventhRandomString, eighthRandomString, ninthRandomString]
let imageDataArray = imageArray.map { (image) -> NSData in
return UIImagePNGRepresentation(image as! UIImage)!
}

let countSet = NSCountedSet(array: imageDataArray)
for imageData in imageDataArray {
let count = countSet.countForObject(imageData)
if count > 5 {
correct = 5
}
}
}

@IBAction func PlayerPRESSED(sender: AnyObject) {
if correct == 5 {
view.backgroundColor = UIColor.greenColor()
}
}

我尝试了代码,但它不会执行该操作。 (view.backgroundColor) 有人知道这段代码有什么问题吗?

最佳答案

这里的逻辑需要与 View 分开。

在保存 UIImage 数组的同一类中创建一个模型。使用此数组填充您的卡片,并检查是否有超过 5 个图像相同。未经测试和未优化的代码示例:

var images = [UIImage]() 

private func populateImages() {
// Fill images array, and perhaps populate imageViews
}

private func checkImageDuplication() {
let imageDataArray = imageArray.map { (image) -> NSData in
return UIImagePNGRepresentation(image)!
}

let countSet = NSCountedSet(array: imageDataArray)
for imageData in imageDataArray {
let count = countSet.countForObject(imageData)
if count > 5 {
// Handle here
}
}
}

关于swift - UIImageView 的 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34637434/

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