0

我正在尝试从第二个 ViewController 中创建的另一个函数()调用我的第一个 ViewController 中创建的函数()。

这是一个在 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)

}

}
4

2 回答 2

0

调用它,unwindToViewController而不需要在第一个视图控制器不可见时调用它

于 2019-01-15T14:47:10.270 回答
0

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

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

以下是一些基本步骤:

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

例如:

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

在 ExcerciseChooserViewController 中:

class ExcerciseChooserViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    private var chosenExercise: String?

    // 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!)

        chosenExercise = excerciseChosen
    }

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

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destinationVC = segue.destination as? ViewController {
            destinationVC.changeText(chosenExercise)
        }
    }
}
于 2019-01-15T15:24:28.843 回答