我有一个快速类,它从文本文档中读取行并打印出第一行。之后,每次单击按钮时,都会读出一个新行。
我想要的是第一次打印出随机行,然后在每次按钮点击后打印出一个随机行。
这是我到目前为止所拥有的:
import Foundation
import UIKit
class InfoController: UIViewController {
// MARK: Properties
@IBOutlet weak var difficultylevel: UILabel!
var i:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func readFile(){
if let path = NSBundle.mainBundle().pathForResource("easymath", ofType: "txt"){
var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)
if let content = data {
let myStrings = content.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
let randomIndex = Int(arc4random_uniform(UInt32(myStrings.count)))
difficultylevel.text = myStrings[randomIndex]
}
}
}
@IBAction func difficultybutton(sender: UIButton) {
difficultylevel.text = // TODO insert random index of "myStrings" array here
}
}
但是,我无法在按钮单击内的TODO部分访问myStrings数组。有关如何设置的任何帮助吗?
答案 0 :(得分:1)
Swift中的变量范围仅限于函数的括号。因此,要在myStrings
函数之外使readFile()
可用,您需要将其声明为该类的属性:
@IBOutlet var difficultyLevel: UILabel? // BTW your IBOutlet should not be weak
var i: Int = 0
var myStrings: [String]?
由于您将反复使用随机功能,我们可以像这样抽象函数
func randomString() -> String? {
if let strings = myStrings {
let randomIndex = Int(arc4random_uniform(UInt32(myStrings.count)))
return strings[randomIndex]
}
return nil
}
然后你的实例化就像这样
if let content = data {
myStrings = content.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
difficultyLevel.text = randomString()
}
然后,您的difficultybutton
函数将(使用抽象的随机字符串函数)
// Changed the name for better readibility
@IBAction func difficultyButtonTapped(sender: UIButton) {
difficultyLevel.text = randomString()
}
最后,没有任何代码调用readFile
函数,因此您应该将其添加到viewDidLoad
函数中,因为@CharlesCaldwell指出
override func viewDidLoad() {
super.viewDidLoad()
readFile()
}