Ios 自定义视图TextField如何计算TextField总和
我正在swift 3.0的iOS应用程序中工作,我正在使用textfield和按钮创建自定义视图,计算所有文本字段的值,并在顶部totalText上显示所有textfield的总和Ios 自定义视图TextField如何计算TextField总和,ios,swift,Ios,Swift,我正在swift 3.0的iOS应用程序中工作,我正在使用textfield和按钮创建自定义视图,计算所有文本字段的值,并在顶部totalText上显示所有textfield的总和 MainViewController的代码: @IBOutlet weak var totalText: UITextField! var totalview:[UIView]! override func viewDidLoad() { yvalue = 1 tag = 1 count =
MainViewController的代码
:
@IBOutlet weak var totalText: UITextField!
var totalview:[UIView]!
override func viewDidLoad() {
yvalue = 1
tag = 1
count = 1
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func actionButton(_ sender: UIButton) {
yvalue = 55 + yvalue
//for i in 0...count {
extraview = View(frame: CGRect(x: 50, y: 75+yvalue, width: 350, height: 50))
extraview.backgroundColor = UIColor(white: 1, alpha: 0.5)
extraview.layer.cornerRadius = 15
extraview.tag = tag
print("ExtraView tag=",extraview.tag)
extraview.ActionButtonsub.addTarget(self, action: (#selector(cancelbutton(_:))), for: UIControlEvents.touchUpInside)
extraview.textFiled.addTarget(self, action: #selector(didChangeTexts(textField:)), for: .editingChanged)
extraview.textFiled.tag = tag
print("text tag=",extraview.textFiled.tag)
self.view.addSubview(extraview)
count = count + 1
tag = tag + 1
//}
}
func cancelbutton(_ sender: UIButton) {
extraview.removeFromSuperview()
}
func didChangeTexts(textField: UITextField) {
totalText.text = extraview.textFiled.text
}
ui视图的代码
:
class View: UIView {
@IBOutlet var subView: UIView!
@IBOutlet weak var textFiled: UITextField!
@IBOutlet weak var ActionButtonsub: UIButton!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
Bundle.main.loadNibNamed("View",owner: self, options:nil)
self.addSubview(self.subView)
}
override init(frame: CGRect) {
super.init(frame: frame)
Bundle.main.loadNibNamed("View", owner: self, options: nil)
subView.frame = bounds
self.addSubview(self.subView)
}
}
类似的功能应该可以正常工作,可能需要稍作修改 您只需要迭代子视图,获取每个视图的文本字段,转换为双值,并将它们相加
func calculateTotal() -> Double {
var total: Double = 0.0
for subview in self.view.subviews {
if let v = subview as? View, !v.textFiled.isEmpty {
total += Double(v.textFiled.text)
}
}
return total
}
如果您认为@Scriptable方式很复杂,请按照下面的方式操作
简单的方法是,您可以在创建和循环集合时将这些文本字段添加到一个集合中。另一种方法是应用
filter
、flatMap
和reduce
函数
let sum = (view.subviews.filter{$0 is View} as! [View]) // filters all `View` instances
.flatMap{$0.textFiled.text} // maps all text properties != nil
.flatMap{Double($0)} // maps all values which are convertible to Double
.reduce(0.0, {$0 + $1}) // calculates the sum
你的问题是?如何从more textfield中获取值并显示总textfield值以显示top TotalTextFiled不确定为什么有人编辑了此文件并添加了一个中断。。我们希望遍历所有文本字段,而不仅仅是第一个文本字段@Karthikbut提问者创建了唯一一个文本字段,它基于一个变量,有一个计数器/循环被注释掉。用户表示“按钮计算所有文本字段的值并显示总和”所有值。一切都表明>=1老实说,我的解决方案的工作量大致相同。无论哪种方式都是好的。我这样做是为了用户不需要重写他们已经做过的