How to programmatically add a UISegmentedControl to a container view

后端 未结 7 937
情话喂你
情话喂你 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:46

    Step 1. Create segment control with index values

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"common-bg.jpg"]];
        [self.navigationItem setHidesBackButton:YES];
    
        //-- For creating segment control in navigation bar
         UISegmentedControl *mainSegment = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Back", @"Month", @"Year", @"Home", nil]];
        [mainSegment setSegmentedControlStyle:UISegmentedControlStyleBar];
        mainSegment.frame = CGRectMake(0,0, 400, 43);
        self.navigationItem.titleView = mainSegment;
        mainSegment.selectedSegmentIndex = 1;
        [mainSegment addTarget:self action:@selector(mainSegmentControl:) forControlEvents: UIControlEventValueChanged];
        [self.view addSubview:mainSegment];
        //--**--
    
    }
    

    Step 2. Create subview

    - (void)mainSegmentControl:(UISegmentedControl *)segment
    {
    
        if(segment.selectedSegmentIndex == 0)
        {
            // action for the first button (Current or Default)
        }
        else if(segment.selectedSegmentIndex == 1)
        {
            // action for the second button 
        }
        else if(segment.selectedSegmentIndex == 2)
        {
            // action for the third button 
        } 
        else if(segment.selectedSegmentIndex == 3)
        {
            // action for the fourth button 
        }
    }
    
    0 讨论(0)
提交回复
热议问题