gpt4 book ai didi

ios - 从另一个类读取/写入 UITextField

转载 作者:行者123 更新时间:2023-11-28 10:37:21 25 4
gpt4 key购买 nike

我有一个包含多个文本字段的 View ,我想从 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
}
}

数学函数.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
}
}

最佳答案

将您的 MathFunctions 更改为结构,并将其函数更改为 static。现在您可以从任何地方调用 MathFunctions.perimeter()

关于ios - 从另一个类读取/写入 UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52690697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com