自定义视图TextField如何计算TextField总和

时间:2017-05-11 11:22:42

标签: ios swift

我正在使用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", owner: self, options: nil)
        subView.frame = bounds
        self.addSubview(self.subView)
    }
}

Sample Output

3 个答案:

答案 0 :(得分:0)

这样的事情应该有用,可能需要一点修改。

您只需要遍历子视图,获取每个视图的文本字段,转换为double值并沿途添加它们。

Target  0.054099
Current time    0.044101
Delay   0.009998

Target  0.064099
Current time    0.045622
Delay   0.018477

Target  0.074099
Current time    0.046161
Delay   0.027937999999999998

Target  0.084099
Current time    0.0465
Delay   0.037598999999999994

Target  0.09409899999999999
Current time    0.046877
Delay   0.047221999999999986

Target  0.10409899999999998
Current time    0.047211
Delay   0.05688799999999998

Target  0.11409899999999998
Current time    0.047606
Delay   0.06649299999999997

答案 1 :(得分:0)

如果您认为@Scriptable的方式很复杂,那就像下面这样..

简单来说,您可以在创建和创建时将这些文本字段添加到一个集合中。当你需要做某事时循环它。

答案 2 :(得分:0)

另一种方法是应用filterflatMapreduce函数

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