我正在使用
swift 3.0中的iOS应用程序,我正在创建自定义视图,文本字段和按钮计算所有文本字段的值,并显示顶部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",options: nil) subView.frame = bounds self.addSubview(self.subView) } }
解决方法
如果您认为@Scriptable的方式很复杂,那就像下面一样..
简单来说,您可以将这些文本字段添加到一个集合中,同时创建&当你需要做某事时循环它.