ProgramingTip

UISegmentedControl을 컨테이너보기에 프로그래밍 방식으로 추가하는 방법

bestdevel 2020. 12. 2. 21:40
반응형

UISegmentedControl을 컨테이너보기에 프로그래밍 방식으로 추가하는 방법


에 대한 프레임을 어떻게 정의 UISegmentedControl하십니까? 세그먼트 컨트롤이 container view의 맨 아래에 나타나기를 원합니다 UIView.


이건 내가 테스트 한 완벽 해 .....

UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 435)];
 scroll.contentSize = CGSizeMake(320, 700);
 scroll.showsHorizontalScrollIndicator = YES;

 NSArray *itemArray = [NSArray arrayWithObjects: @"One", @"Two", @"Three", nil];
 UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
 segmentedControl.frame = CGRectMake(35, 200, 250, 50);
 segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
 [segmentedControl addTarget:self action:@selector(MySegmentControlAction:) forControlEvents: UIControlEventValueChanged];
 segmentedControl.selectedSegmentIndex = 1;     
 [scroll addSubview:segmentedControl];
 [segmentedControl release]; 
 [self.view addSubview:scroll];

그런 다음 수업에 메소드를 추가하십시오.

- (void)MySegmentControlAction:(UISegmentedControl *)segment 
{    
        if(segment.selectedSegmentIndex == 0)
        {
            // code for the first button
        } 
}

더 이상 사용하지 않는 UISegmentedControlStyle의 경우이 URL을 볼 수 있습니다 .


이렇게 할 수있어 ...

UISegmentedControl *segmentControl = [[UISegmentedControl alloc]initWithItems:@[@"One",@"Two"]];

[segmentControl setSegmentedControlStyle:UISegmentedControlStyleBar];
segmentControl.frame = CGRectMake(10, 50, 300, 30);
[segmentControl addTarget:self action:@selector(segmentedControlValueDidChange:) forControlEvents:UIControlEventValueChanged];
[segmentControl setSelectedSegmentIndex:0];
[scrollView addSubview:segmentControl];
[segmentControl release];

2 단계 :

-(void)segmentedControlValueDidChange:(UISegmentedControl *)segment
{
switch (segment.selectedSegmentIndex) {
    case 0:{
        //action for the first button (Current)
        break;}
    case 1:{
        //action for the first button (Current)
        break;}
    }
}

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
        }
    }
}

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. 세그먼트 값을 배열을 만듭니다.

  2. 배열을 사용하여 세그먼트 초기화
  3. 화면에 위치를 지정하고 컨트롤 크기를 조정합니다.
  4. 사용자가 상호 작용할 때 호출되는 메서드를 가리립니다.
  5. 언어 (이 경우 Dos)를 선택합니다.
  6. 메인 뷰에 배치

그런 다음 사용자가 값을 설명 할 때 호출되는 segmentAction 메서드를 만듭니다.

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

보기가 더 깨끗하기 때문에 switch 문을 선호합니다. 열거 형을 만들고 0,1,2 대신 옵션 (optionUno, optionDos, optionTres)에 대한 값을 사용하여 개선 할 수 있습니다.


1 단계. 인덱스 값으로 세그먼트 컨트롤 만들기

- (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];
    //--**--

}

2 단계. 하위보기 만들기

- (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 
    }
}

UISegmentedControl을 프로그래밍 방식으로 컨테이너보기에 추가하려면 다음 단계를 따르세요.

// Create UISegmentedControl object to add control UISegment.
UISegmentedControl *objSegment = [[UISegmentedControl alloc] initWithItems:array];

// Set frame for objSegment Control (formate: (x, y, width, height)). where, y = (height of view - height of control). 
[objSegment setFrame:CGRectMake(0, (self.view.frame.size.height - 40), 320, 40)];

// handle UISegmentedControl action.
[objSegment addTarget:self action:@selector(handleSegmentControl:) forControlEvents: UIControlEventValueChanged];

 // Add your UISegmentedControl in your view.
[self.view addSubview:objSegment];

질문이 있으시면 저에게 연락하십시오.


이는 모든 유형의 iOS 기기에서 작동합니다.

UISegment *segment = [[UISegmentedControl alloc] initWithItems:array];
segment.frame = CGRectMake(0, self.view.frame.size.height - 40, 300, 40);
UIFont *font = [UIFont fontWithName:@"DroidSans" size:18.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
                                                       forKey:NSFontAttributeName];
[segment setTitleTextAttributes:attributes
                                forState:UIControlStateNormal];
[segment addTarget:self action:@selector(segmentAction:) forControlEvents: UIControlEventValueChanged];
[self.view addSubview:segment];

빠른:

let items = ["All Fruits", "Orange", "Grapes", "Banana"]
let filtersSegment = UISegmentedControl(items: items)
filtersSegment.frame = CGRect.init(x: 0, y: 0, width: 300, height: 50)
filtersSegment.selectedSegmentIndex = 0
filtersSegment.tintColor = UIColor.black
filtersSegment.addTarget(self, action: #selector(self.filterApply), for: UIControlEvents.valueChanged)
self.view.addSubview(filterSegment)

@objc private func filterApply(segment: UISegmentedControl) -> Void {
    switch segment.selectedSegmentIndex {
    case 1:
        //Do something for Orange
    case 2:
        //Do something for Grapes
    case 3:
        //Do something for Banana
    default:
        //Do something for All Fruits
    }
}

참고 URL : https://stackoverflow.com/questions/6688160/how-to-programmatically-add-a-uisegmentedcontrol-to-a-container-view

반응형