为什么这个快速代码不能正常工作?

时间:2016-06-21 00:19:49

标签: ios swift

我一直在学习swift很短的时间,并在xcode中设计了一个简单的ios swift应用程序来打开警报并在点击时在标签内显示开发人员名称。代码发布在下面。出于某种原因,在label.hidden = true上,我收到一条错误说"期望声明",但没有别的。为什么会收到此错误消息,这是什么意思?

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//declares the label
let label = UILabel(frame: CGRectMake(0, 0, 200, 21))
//should hide the label
label.hidden = true
//next 2 lines center the label
label.center = CGPointMake(160, 284)

label.textAlignment = NSTextAlignment.Center
//puts text into the label
label.text = "This app was developed by me!"

//declares the function
@IBAction func function() {
    // declares variable that stores the alert and it's properties
    let alertController = UIAlertController(title: "Welcome!", message: "Here is some information about the developer!", preferredStyle: .Alert)
    alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alertController, animated: true, completion: nil)
    label.hidden = false


    }
}

1 个答案:

答案 0 :(得分:2)

您需要使用函数封装它。

class ViewController: UIViewController {

  let label = UILabel(frame: CGRectMake(0, 0, 200, 21))

  override func viewDidLoad() {
    super.viewDidLoad()

    configureViews()
  }

  func configureViews() {
    //declares the label
    //should hide the label
    label.hidden = true
    //next 2 lines center the label
    label.center = CGPointMake(160, 284)

    label.textAlignment = NSTextAlignment.Center
    //puts text into the label
    label.text = "This app was developed by me!"
  }


  //declares the function
  @IBAction func function() {
    // declares variable that stores the alert and it's properties
    let alertController = UIAlertController(title: "Welcome!", message: "Here is some information about the developer!", preferredStyle: .Alert)
    alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alertController, animated: true, completion: nil)
    label.hidden = false
  }
}