简体   繁体   English

如何通过按一个按钮从一个数组中随机快速地引出一个简单的报价?

[英]How to print by press of a button a simple quote in swift at random from an array?

I am completely new to coding. 我是编码的新手。

I started using this app called MIMO and learned a few bits and pieces. 我开始使用这个名为MIMO的应用程序,并学到了一些点点滴滴。 In one chapter they let us code a simple "dice app" where by pressing a button a number from 1 - 6 appears. 在一个章节中,他们使我们编写了一个简单的“骰子应用”,其中通过按按钮可以显示1-6之间的数字。 Now I wanted to rewrite that so that at the button press the app displays a quote from a predetermined array. 现在,我想重写它,以便在按下按钮时,应用程序显示来自预定数组的报价。

I am completely stuck, however. 但是,我完全被困住了。

Here's what I got: 这是我得到的:

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var quotesLabel: UILabel!

    let quotes = ["Quote1!", "Quote2!"]
    let randomIndex = Int(arc4random_uniform(UInt32(quotes.count)))
    let randomQuote = quotes[randomIndex]
    print(array[randomIndex])

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Basically any arbitrary code must be run in a method, in this case in an IBAction which is triggered when the button is pressed. 基本上,任何任意代码都必须在方法中运行,在这种情况下,是在IBAction ,该操作在按下按钮时触发。 The method viewDidLoad is not needed. 不需要viewDidLoad方法。

  • Change the code to 将代码更改为

     import UIKit class ViewController: UIViewController { @IBOutlet weak var quotesLabel: UILabel! let quotes = ["Quote1!", "Quote2!", "Quote3!", "Quote4!"] @IBAction func showRandomQuote(_ sender : UIButton) { let randomIndex = Int(arc4random_uniform(UInt32(quotes.count))) let randomQuote = quotes[randomIndex] quotesLabel.text = randomQuote } } 
  • In Interface Builder drag a button into the canvas of the view controller 在Interface Builder中,将一个按钮拖到视图控制器的画布中

  • Connect ( - drag ) the button to the IBAction and the label to the IBOutlet 连接(^ - 拖动 )的按钮IBAction和标签的IBOutlet
  • Run the app and press the button 运行应用程序,然后按按钮

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

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