How to programmatically add a UISegmentedControl to a container view

后端 未结 7 952
情话喂你
情话喂你 2020-12-12 17:54

How would I define the frame for a UISegmentedControl? I would like the segmented control to appear at the bottom of a container view i.e UI

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 18:39

    Updated answer for Swift 4.x:

    class SegmentClass: UIViewController {
        func addControl()  {
            let items = ["Uno", "Dos", "Tres"]
            let segmentedControl = UISegmentedControl(items: items)
            segmentedControl.frame = CGRect(x: 35, y: 200, width: 250, height: 50)
            segmentedControl.addTarget(self, action: #selector(segmentAction(_:)), for: .valueChanged)
            segmentedControl.selectedSegmentIndex = 1
            view.addSubview(segmentedControl)
        }
    
        @objc func segmentAction(_ segmentedControl: UISegmentedControl) {
            switch (segmentedControl.selectedSegmentIndex) {
            case 0:
                break // Uno
            case 1:
                break // Dos
            case 2:
                break // Tres
            default:
                break
            }
        }
    }
    

    Original answer in Objective-C:

    NSArray *itemArray = [NSArray arrayWithObjects: @"Uno", @"Dos", @"Tres", nil];
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
    segmentedControl.frame = CGRectMake(35, 200, 250, 50);
    [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents: UIControlEventValueChanged];
    segmentedControl.selectedSegmentIndex = 1;
    [self.view addSubview:segmentedControl];
    
    1. Create an array to store the values for the segment
    2. Initialize the segment using the array
    3. Assign it a location on the screen & size the control
    4. Point it towards a method that is called when the user interacts with it
    5. Select a default value (in this case, Dos)
    6. Place it on the main view

    Then create the segmentAction method that is called when the user changes a value

    - (void)segmentAction:(UISegmentedControl *)segment
    {
        switch (segment.selectedSegmentIndex) {
            case 0:
                // Uno
                break;
            case 1:
                // Dos
                break;
            case 2:
                // Tres
                break;
            default:
                break;
        }
    }
    

    I just prefer the switch statement because it is cleaner to look at. You can improve it by creating an enum and using the values in it for the options (optionUno,optionDos,optionTres) instead of 0,1,2.

提交回复
热议问题