从另一个类读取/写入UITexTField

时间:2018-10-07 16:45:31

标签: ios swift

我有一个包含几个文本字段的视图,我想从viewController中读取它们,进行验证,然后在另一个文件中的另一个类中调用一个函数以写出结果。

我知道我可以返回结果并从ViewController中将其写入,但是某些函数(此处未显示)具有如此多的输入和输出字段,以至于将它们传回似乎非常复杂。我该怎么做呢?我可以做吗? (或者我只是想编写非常糟糕的代码?)

这是我目前拥有的简化版本:

MainViewController.swift:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var fieldLength1: UITextField!  
    @IBOutlet weak var fieldLength2: UITextField!
    @IBOutlet weak var fieldLength3: UITextField!
    @IBOutlet weak var fieldLength4: UITextField!    
    @IBOutlet weak var fieldPerimeter: UITextField!    
    @IBOutlet weak var fieldArea: UITextField!    

    override viewDidLoad() {
        super.viewDidLoad()

        fieldLength1.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
        fieldLength2.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
        fieldLength3.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
        fieldLength4.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)

    }

    @objc func textFieldDidChange() _ textField: UITextField) {
        if isValidEntry(textField: textField) {
            // Here is where I would like to call the function in the other class
            // Something like:
            // MathFunc().perimeter(
            // MathFunc().area
        }
    }

    func isValidEntry() {
        // ensure entries are only numbers and that enough info is present for calculations
    }
}

MathFunctions.swift:

import Foundation

class MathFunctions {
    func perimeter(l1: Double, l2:Double, l3:Double, l4:Double) -> Double {
        let p = l1 + l2 + l3 + l4    
        // Here is where I would like to write the result to the UITextField
        // Something like:
        // fieldPerimeter.text = p //with some formatting not shown here
    }

    func area(width: Double, length:Double) -> Double {
        let rectArea = width * length 
        // Here is where I would like to write the result to the UITextField
        // Something like:
        // fieldArea.text = rectArea //with some formatting not shown here
    }
}

2 个答案:

答案 0 :(得分:2)

将MathFunctions更改为结构,并将其功能更改为static。现在您可以在任何地方说MathFunctions.perimeter()

答案 1 :(得分:1)

首先,我认为fieldPerimeterfieldArea应该是标签,而不是文本字段。它们是输出,而不是输入。

第二,请记住area(width:length:) 返回结果。在视图控制器中调用该函数,然后将结果推送到字段中。

假设是视图控制器,它将值推入标签。