gpt4 book ai didi

ios - 随机字符串和 UIImageView 在一起

转载 作者:行者123 更新时间:2023-11-28 15:09:25 25 4
gpt4 key购买 nike

我正在开发一款应用程序,它可以让用户在您摇动设备时获得随机数据。

我有 4 个数组来保存字符串数据和创建随机数的函数;

let characters = ["Zoolog", "Xander"]

let problems = ["Asteroid", "Dr Evil"]

let places = ["Vast Desert", "Ice Caves"]

let time = ["Wednesday 12th, 1220", "1236"]



func randomCharacter() -> String {

let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: characters.count)

return characters[randomNumber]

}

func randomPlaces() -> String {

let randomNumberOne = GKRandomSource.sharedRandom().nextInt(upperBound: places.count)

return places[randomNumberOne]
}

func randomProblems() -> String {

let randomNumberTwo = GKRandomSource.sharedRandom().nextInt(upperBound: problems.count)

return problems[randomNumberTwo]

}

func randomTime() -> String {

let randomNumberThree = GKRandomSource.sharedRandom().nextInt(upperBound: time.count)

return time[randomNumberThree]
}

在我的 viewController 上,数据是随机的,用户在摇动设备后会在屏幕上看到随机数据。

 override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if(event?.subtype == UIEventSubtype.motionShake) {

characterName.text = myStoryCharacters.randomCharacter()
placeName.text = myStoryCharacters.randomPlaces()
problemName.text = myStoryCharacters.randomProblems()
timeName.text = myStoryCharacters.randomTime()

}
}

我还有一个人物图片的imageView。因此,一旦数据被随机化,我希望我的用户也能看到角色和他们的名字。但目前,我只能随机化 imageView 和字符分开

我看过一些示例代码,但无法理解如何处理这个问题。

--已更新注意:我的代码没有问题。我不知道如何随机化 characterImageView 以匹配 characterName。因此,如果一张图片属于我的字符数组中的一个字符,那么 nameLabel 和 imageView 应该匹配。

override func viewDidLoad() {
super.viewDidLoad()
super.becomeFirstResponder()
// Do any additional setup after loading the view, typically from a nib.

characterImageView.image = UIImage(named: "elegantEmma")
placeImageView.image = UIImage(named: "zombieLand")
problemImageView.image = UIImage(named: "meteor")
timeImageView.image = UIImage(named: "time")

//First random value shown on the launch
characterName.text = myStoryCharacters.randomCharacter()
placeName.text = myStoryCharacters.randomPlaces()
problemName.text = myStoryCharacters.randomProblems()
timeName.text = myStoryCharacters.randomTime()

最佳答案

您还需要将图像名称存储在数组中,因此例如您的角色有...

let characters = ["Zoolog", "Xander"]
let characterImages = ["ZoologImage", "XanderImage"] // These relate to the image names in your assets

func randomCharacter() -> String {

let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: characters.count)

characterImageView.image = UIImage(named: characterImages[randomNumber])

return characters[randomNumber]

}

然后对其他数组做同样的事情,你也可以改变随机函数来设置文本而不是费心返回它,除非你当然需要它来做其他事情

关于ios - 随机字符串和 UIImageView 在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47906649/

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