简体   繁体   English

如何查找在ViewDidLoad中调用的UIImage的值,并传递到Swift中的另一个函数

[英]How to find value of UIImage called in ViewDidLoad, pass to another function in Swift

I am using a simple function to call a random image when a view controller is loaded. 我正在使用一个简单的函数在加载视图控制器时调用随机图像。

override func viewDidLoad() {
    super.viewDidLoad()
    var randomtest = ReturnRandom()
    mainImage.image = UIImage(named: randomtest)
}

I want a button's action to be based on what image was displayed. 我希望按钮的动作基于所显示的图像。 For example 例如

@IBAction func Button1(sender: AnyObject) { 
switch randomtest {
case 1: //Do something here
case 2: //Do something different here
default:  
}

However I can not figure out how to get the value of "randomtest" out of ViewDidLoad. 但是我不知道如何从ViewDidLoad中获取“ randomtest”的值。 I also can not seem to create the random number outside the ViewDidLoad then pass the variable in. Sorry I'm new to all this, iOS development is a long way away from php... 我似乎也无法在ViewDidLoad之外创建随机数,然后将变量传递给我。对不起,我是所有这一切的新手,iOS开发距离php还有很长的路...

The reason I was having trouble declaring the result of my function as a instance variable is that my function is also an instance function . 我无法将函数的结果声明为实例变量的原因是我的函数也是实例函数 I can not call it, there has been no instance. 我不能称呼它,没有实例。 So this 所以这

class ViewController : UIViewController {

var randomtest: Int = ReturnRandom();

Will return a "Missing argument for parameter #1 in call" For more details please check out this very helpful thread on setting initial values . 将返回“调用中参数#1的缺少参数”。有关更多详细信息,请查看有关设置初始值的非常有用的线程。 Since my function was so simple I just computed the property while setting the initial value, no need for an additional class level function. 由于我的函数非常简单,因此我仅在设置初始值时计算了属性,因此无需其他类级别的函数。

dynamic var randomtest:String {
let imageNumber = arc4random_uniform(3)
var imageString = String(imageNumber)
return (imageString)}

Hope this helps someone. 希望这对某人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM