0

I am using the following code to create a custom switch:

UISegmentedControl* switchView=[[UISegmentedControl alloc] 
                                initWithItems:[[NSMutableArray alloc] initWithObjects:@"On",@"Off",nil]];
[switchView setFrame:CGRectMake(20,365,140,28)];
switchView.selectedSegmentIndex=0;
switchView.segmentedControlStyle=UISegmentedControlStyleBar;
[switchView setImage:[UIImage imageNamed:@"onSelected.png"] forSegmentAtIndex:0];
[switchView setImage:[UIImage imageNamed:@"off.png"] forSegmentAtIndex:1];
[switchView addTarget:self action:@selector(checkOnOffState:) forControlEvents:UIControlEventValueChanged];

I would now like to add this control to one of my screens (I believe the correct term is ViewController?). How would I do this in Xcode 4.3?

I looked at a few other posts and was not able to find anything that works. For example, How do I add a custom view to iPhone app's UI? suggested something along the lines of [[myVC view] addSubview:myView]; and How to customize UISwitch button in iphone? suggested self.navigationItem.titleView=switchView; If possible, could you also explain why these approaches did not work? Thanks.

Community
  • 1
  • 1
abw333
  • 5,571
  • 12
  • 41
  • 48

2 Answers2

1

You need to create a class for your switch which is subclass of your UISegmentControl , Else you can add this code in your vc directly as well.

Add this code in its initWithFrame method

and then use it in your VC

-(void)viewDidLoad{
  urCustomSwitch  = [urCustomSwitch alloc] initWithFrame:CGRectMake(20,365,140,28)];
  [self.view addSubview:urCustomSwitch];
}

This shall serve your purpose if you are to create custom reusable class.

DivineDesert
  • 6,924
  • 1
  • 29
  • 61
  • Thank you for your response. Should I make this class a subclass of UITableViewController, UITableViewCell, AppDelegate, CIColor, or CIContext. I would have though that I should make this a subclass of UIView, but that is not one of the options. Thanks again. – abw333 Jul 10 '12 at 03:56
  • 1
    U can make it a subclass of `UISegmentControl` or `UIView` is also an option – DivineDesert Jul 10 '12 at 03:58
  • This is not working for me because my custom switch does not have an alloc method. Is there something that I have to do to be able to use it or do I have to instantiate it in another way? – abw333 Jul 11 '12 at 03:22
  • If you subclass any UIControl or UIView, you need to override this method and in which you will write your code. – DivineDesert Jul 11 '12 at 04:06
0

If you add this switch control i.e. UISegmentedControl in InterfaceBuilder (.xib file)

This task will be much easier for you.

ajacian81
  • 7,419
  • 9
  • 51
  • 64
120hit
  • 1,026
  • 7
  • 6
  • do you mean adding my custom class that is a subclass of UISegmentedControl to the InterfaceBuilder. Can I do this just by creating the .xib file? Thanks. – abw333 Jul 11 '12 at 03:20