UIStepper increment dynamic text box

1k Views Asked by At

I'm currently making setting up three-page form in Swift, with dynamically-created labels, UITextFields, and UISteppers. However, I'm stuck wondering how to increment the UITextField dynamically, since every example uses the storyboard, and I'm doing it programatically. Thanks in advance for your help!

           // 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)

EDIT: is it similar to how we add actions to buttons? How to create a button programmatically?

1

There are 1 best solutions below

1
On

Since UIStepper is a subclass of UIControl, you can use addTarget(_:action:forControlEvents:) to set the action to happen. The control event should be UIControlEvents.ValueChanged to trigger the action properly.

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

Beyond that you'll need some way to relate the UIStepper to the related UITextField that is associated with it. So you'll need to store the UITextFields and UISteppers in some sort of array as a tuple, or you can sub-class UIStepper and add a property to the UITextField that is associated with that particular stepper.