我正在开发一个应用程序,当你摇动你的设备时,它可以让用户获得随机数据。
我有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和字符分开随机,而不能一起随机。
我已经看过一些示例代码,但不知道如何处理这个问题。
--更新
注意:我的代码没有问题。我不知道如何随机化characterImageView以匹配characterName。因此,如果图片属于我的字符数组中的字符,则名称标签和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/