簡體   English   中英

如何通過按一個按鈕從一個數組中隨機快速地引出一個簡單的報價?

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

我是編碼的新手。

我開始使用這個名為MIMO的應用程序,並學到了一些點點滴滴。 在一個章節中,他們使我們編寫了一個簡單的“骰子應用”,其中通過按按鈕可以顯示1-6之間的數字。 現在,我想重寫它,以便在按下按鈕時,應用程序顯示來自預定數組的報價。

但是,我完全被困住了。

這是我得到的:

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()
    }
}

基本上,任何任意代碼都必須在方法中運行,在這種情況下,是在IBAction ,該操作在按下按鈕時觸發。 不需要viewDidLoad方法。

  • 將代碼更改為

     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 } } 
  • 在Interface Builder中,將一個按鈕拖到視圖控制器的畫布中

  • 連接(^ - 拖動 )的按鈕IBAction和標簽的IBOutlet
  • 運行應用程序,然后按按鈕

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM