UIStepper增量动态文本框

时间:2014-12-03 21:05:32

标签: ios swift uitextfield uistepper

我目前正在使用动态创建的标签,UITextFields和UISteppers在Swift中设置三页表单。但是,我很想知道如何动态增加UITextField,因为每个例子都使用了故事板,而我是以编程方式进行的。在此先感谢您的帮助!

           // read triggers configs
        let triggers = dict["Triggers"] as Array<String>

        //add list of triggers to view
        var triggersView = UIView(frame: frame)
        var prevInput = 150;
        for index in 0..<triggers.count{
            //title for triggers page
            var title = UILabel(frame: CGRectMake(0, 0, 300, 50))
            title.center = CGPointMake(200, 60)
            title.font = UIFont(name: title.font.fontName, size: 28)
            title.text = "Triggers"
            triggersView.addSubview(title)

            //label for trigger
            var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
            label.center = CGPointMake(160, CGFloat(prevInput))

            label.textAlignment = NSTextAlignment.Left
            label.text = triggers[index]
            triggersView.addSubview(label)

            //input box for trigger
            var input = UITextField(frame: CGRectMake(0, 0, 50, 21))
            input.center = CGPointMake(300, CGFloat(prevInput))
            input.text = "0";
            triggersView.addSubview(input);

            //UIStepper
            var stepper = UIStepper(frame: CGRectMake(0, 0, 50, 21))
            stepper.center = CGPointMake(350, CGFloat(prevInput))
            stepper.
            triggersView.addSubview(stepper);

            prevInput += 75 //increment for height

        }
        self.scrollView.addSubview(triggersView)
编辑:是否类似于我们如何向按钮添加操作? How to create a button programmatically?

1 个答案:

答案 0 :(得分:1)

由于UIStepper是UIControl的子类,因此您可以使用addTarget(_:action:forControlEvents:)来设置要执行的操作。控制事件应为UIControlEvents.ValueChanged以正确触发操作。

https://developer.apple.com/LIBRARY/IOS/documentation/UIKit/Reference/UIControl_Class/index.html#//apple_ref/occ/instm/UIControl/addTarget:action:forControlEvents

除此之外,您还需要一些方法将UIStepper与与之关联的相关UITextField相关联。因此,您需要将UITextFields和UISteppers作为元组存储在某种数组中,或者您可以将UIStepper子类化,并将属性添加到与该特定步进器关联的UITextField。