从firstFile.swift / viewController调用secondFile.swift / viewController中的函数吗?

时间:2019-01-15 14:22:18

标签: ios swift

我试图从第二个ViewController中的另一个function()调用第一个ViewController中的function()。

此功能可更新firstViewController中按钮的标题。

我已经搜索了,但是找不到方法。

第一个ViewController // ViewController.swift

import UIKit


class ViewController: UIViewController, UITextFieldDelegate {

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

}




@IBAction func excerciseChooserButton(_ sender: UIButton) {
}

var weight = 0 {
    didSet {
        weightLabel.text = "\(weight)"
    }
}

// User input WEIGHT

@IBOutlet weak var weightLabel: UITextField!

func textField(_ weightLabel: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
    let withDecimal = (
        string == NumberFormatter().decimalSeparator &&
            weightLabel.text?.contains(string) == false
    )
    return isNumber || withDecimal
}



@IBAction func plusWeight(_ sender: UIButton) {
    weight += 5
}

@IBAction func minusWeight(_ sender: UIButton) {
    weight -= 5
}

// User input REPS


@IBOutlet weak var repLabel: UILabel!

@IBAction func repSlider(_ sender: UISlider) {
    let currentRepValue = Int(sender.value)
    repLabel.text = "\(currentRepValue)"
    let cm = Calculator(weight: weightLabel.text!, reps: repLabel.text!)
    let result = cm.calcRM()
    repMax.text = "1RM: \(result)kg"

}


@IBOutlet weak var repMax: UILabel!

@IBOutlet weak var excerciseLabel: UIButton!

func changeText() {
excerciseLabel.setTitle(Excercises.excChosen, for: .normal)
print(excerciseLabel)
}


@IBAction func unwindToViewController(segue:UIStoryboardSegue) { 
 }
}

// // // //

第二个ViewController // ExcerciseChooserViewController.swift

import UIKit


struct Excercises {
static var excChosen:String? = ""
 }

class ExcerciseChooserViewController: UIViewController, UITableViewDelegate, UITableViewDataSource



// Data model: These strings will be the data for the table view cells
let excercises: [String] = ["Bench Press", "Squat", "Push Press", "Deadlift"]

// cell reuse id (cells that scroll out of view can be reused)
let cellReuseIdentifier = "cell"

// don't forget to hook this up from the storyboard
@IBOutlet var tableView: UITableView!




override func viewDidLoad() {
super.viewDidLoad()

// Register the table view cell class and its reuse id
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

// (optional) include this line if you want to remove the extra empty cell divider lines
// self.tableView.tableFooterView = UIView()

// This view controller itself will provide the delegate methods and row data for the table view.
tableView.delegate = self
tableView.dataSource = self
}

// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.excercises.count
}

// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

// create a new cell if needed or reuse an old one
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

// set the text from the data model
cell.textLabel?.text = self.excercises[indexPath.row]

return cell
}


// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let excerciseChosen = "\(excercises[indexPath.row])"
print("You tapped cell number \(indexPath.row).")
print(excerciseChosen)
goBackToOneButtonTapped((Any).self)
Excercises.excChosen = excerciseChosen
print(Excercises.excChosen!)

// call function to update text

ViewController.changeText()


}





@IBAction func goBackToOneButtonTapped(_ sender: Any) {
    performSegue(withIdentifier: "unwindToViewController", sender: self)

}

}

2 个答案:

答案 0 :(得分:0)

相反,从unwindToViewController调用它,无需在第一个视图控制器不可见时调用它

答案 1 :(得分:0)

有很多方法可以做到这一点,但是我将在这里描述一个简单的方法。

因为要通过segue返回“ ViewController”,所以一个不错的选择是覆盖prepare(for:sender:)。这将为您提供该segue的目标视图控制器的参考,然后将允许您在该视图控制器中调用函数或设置属性。您可以了解有关此方法here的更多信息。

以下是一些基本步骤:

  1. ViewController中,更新您的changeText()方法以接受字符串参数:changeText(_ text: String?)
  2. ExcerciseChooserViewController添加属性以保存要使用的文本:private var chosenExercise: String?
  3. 在tableView:DidSelectRowAtIndexPath:方法中,将新的chosenExercise属性设置为要传递给ViewController的字符串。
  4. prepare(for:sender:)的{​​{1}}中,获取对目标视图控制器的引用,将其向下转换为您的子类ExcerciseChooserViewController,然后调用您的新方法并传递ViewController字符串。

例如:

exerciseText

在ExcerciseChooserViewController中:

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var excerciseLabel: UIButton!

    func changeText(_ text: String?) {
        guard let text = text else { return }

        excerciseLabel.setTitle(text, for: .normal)
        print(excerciseLabel)
    }
}