我正在使用 swift 3.0 开发 iOS 应用程序,我正在使用文本字段和按钮创建自定义 View ,计算所有文本字段的值,并在顶部 totalText 上显示所有文本字段的总和。
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
}
UIView
代码:
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)
}
}
最佳答案
如果您认为@Scriptable 方式很复杂,那么请按照下面的方式进行..
简单的方法,您可以将这些文本字段添加到一个集合中,同时在需要做某事时创建和循环它。
关于ios - 自定义 View TextField 如何计算TextField总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43913993/