【问题标题】:Button perform action from another file (Swift)按钮从另一个文件执行操作(Swift)
【发布时间】:2014-11-16 20:32:41
【问题描述】:

我想点击一个 UIButton 来清除一个 UITextView。我希望按钮操作的代码位于另一个 Swift 文件中。我该怎么做?

谢谢

【问题讨论】:

  • “在另一个 Swift 文件中”是指在不同的视图控制器中,还是只是在扩展同一个视图控制器的单独 .swift 文本文件中?
  • 是的。按钮操作只是一个单独的 .swift 文本文件

标签: swift uibutton uitextview


【解决方案1】:

如果您希望按钮操作位于不同的 Swift 文件中,只需在新文件中为您的 ViewController 创建一个类 extension

ViewController.swift

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var myTextField: UITextField!

    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.
    }
}

ViewControllerExt.swift

import UIKit

extension ViewController {
    @IBAction func coolButton(sender: UIButton) {
        println("cool button pressed")
        myTextField.text = "cool"
    }
}

【讨论】:

  • 这段代码是放在新的 ViewControllerExt.swift 中还是放在 ViewController.swift 中?
  • 这段代码在新的 ViewControllerExt.swift 文件中。
  • 有一条错误消息说“声明仅在文件范围内有效”
  • 您可以在扩展中定义函数,但不能定义新属性。 vars 和 lets 需要在主文件中。您将能够在扩展程序中访问它们。
  • 我不确定我做错了什么。我在 ViewController.swift 中声明了 UITextView,在 ViewControllerExt.swift 中声明了上面的代码。错误在extension ViewController { 的行上
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 2017-02-26
  • 1970-01-01
  • 1970-01-01
  • 2019-05-13
  • 1970-01-01
  • 2019-01-03
相关资源
最近更新 更多