如何以编程方式将 UISegmentedControl 添加到容器视图

发布于 2024-11-23 18:42:52 字数 90 浏览 3 评论 0原文

如何定义 UISegmentedControl 的框架? 我希望分段控件出现在容器视图(即UIView)的底部。

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 UIView.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

南巷近海 2024-11-30 18:42:53

更新了 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 语句,因为它看起来更清晰。您可以通过创建枚举并使用其中的值作为选项(optionUno、optionDos、optionTres)而不是 0、1、2 来改进它。

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.

爺獨霸怡葒院 2024-11-30 18:42:53

你可以这样做...

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

U can do like this...

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];

Step 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;}
    }
}
浅紫色的梦幻 2024-11-30 18:42:53

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

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 
    }
}
泪意 2024-11-30 18:42:53

要以编程方式将 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];

如果您有任何疑问,请与我联系。

To add a UISegmentedControl to a container view programmatically, follow following steps:

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

If you have any query, Contact me.

花辞树 2024-11-30 18:42:53

斯威夫特:

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

Swift:

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
    }
}
溺渁∝ 2024-11-30 18:42:53

这适用于所有类型的 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];

This will work for all type of iOS device:

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];
恏ㄋ傷疤忘ㄋ疼 2024-11-30 18:42:52

我测试过这个是完美的......

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,您可以查看
网址。

this one is perfect I tested.....

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];

Then add your method in your class.

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

For deprecated UISegmentedControlStyle you can take a look on this
URL.

两人的回忆 2024-11-30 18:42:52

尝试此链接:

以编程方式添加分段控制

更新:

import UIKit

class ViewController: UIViewController {

  /**
    Loads the view and in our case we override default loadView to provide
    custom SegmentedControl.
  */
  override func loadView() {
      super.loadView()
      self.view.backgroundColor = UIColor.purpleColor()

      println("Main view's loadView() called.")

      // Initialize
      let items = ["Purple", "Green", "Blue"]
      let customSC = UISegmentedControl(items: items)
      customSC.selectedSegmentIndex = 0

      // Set up Frame and SegmentedControl
      let frame = UIScreen.mainScreen().bounds
      customSC.frame = CGRectMake(frame.minX + 10, frame.minY + 50,
                                  frame.width - 20, frame.height*0.1)

      // Style the Segmented Control
      customSC.layer.cornerRadius = 5.0  // Don't let background bleed
      customSC.backgroundColor = UIColor.blackColor()
      customSC.tintColor = UIColor.whiteColor()

      // Add target action method
      customSC.addTarget(self, action: "changeColor:", forControlEvents: .ValueChanged)

      // Add this custom Segmented Control to our view
      self.view.addSubview(customSC)
  }

  /**
    Handler for when custom Segmented Control changes and will change the
    background color of the view depending on the selection.
   */
  func changeColor(sender: UISegmentedControl) {
      println("Change color handler is called.")
      print("Changing Color to ")
      switch sender.selectedSegmentIndex {
      case 1:
          self.view.backgroundColor = UIColor.greenColor()
          println("Green")
      case 2:
          self.view.backgroundColor = UIColor.blueColor()
          println("Blue")
      default:
          self.view.backgroundColor = UIColor.purpleColor()
          println("Purple")
      }
  }

  override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.
  }

  override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
  }
}

来源:http://www.richardhsu.me/

Try this link:

ADDING A SEGMENTED CONTROL PROGRAMMATICALLY

Updated:

import UIKit

class ViewController: UIViewController {

  /**
    Loads the view and in our case we override default loadView to provide
    custom SegmentedControl.
  */
  override func loadView() {
      super.loadView()
      self.view.backgroundColor = UIColor.purpleColor()

      println("Main view's loadView() called.")

      // Initialize
      let items = ["Purple", "Green", "Blue"]
      let customSC = UISegmentedControl(items: items)
      customSC.selectedSegmentIndex = 0

      // Set up Frame and SegmentedControl
      let frame = UIScreen.mainScreen().bounds
      customSC.frame = CGRectMake(frame.minX + 10, frame.minY + 50,
                                  frame.width - 20, frame.height*0.1)

      // Style the Segmented Control
      customSC.layer.cornerRadius = 5.0  // Don't let background bleed
      customSC.backgroundColor = UIColor.blackColor()
      customSC.tintColor = UIColor.whiteColor()

      // Add target action method
      customSC.addTarget(self, action: "changeColor:", forControlEvents: .ValueChanged)

      // Add this custom Segmented Control to our view
      self.view.addSubview(customSC)
  }

  /**
    Handler for when custom Segmented Control changes and will change the
    background color of the view depending on the selection.
   */
  func changeColor(sender: UISegmentedControl) {
      println("Change color handler is called.")
      print("Changing Color to ")
      switch sender.selectedSegmentIndex {
      case 1:
          self.view.backgroundColor = UIColor.greenColor()
          println("Green")
      case 2:
          self.view.backgroundColor = UIColor.blueColor()
          println("Blue")
      default:
          self.view.backgroundColor = UIColor.purpleColor()
          println("Purple")
      }
  }

  override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.
  }

  override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
  }
}

SOURCE: http://www.richardhsu.me/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文