Segcontrol = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Mind", @"Munches", nil]];
Segcontrol.frame=CGRectMake(CGRectGetWidth(self.view.frame)/4.5, self.view.frame.size.height/4, CGRectGetWidth(self.view.frame)/1.8, CGRectGetHeight(self.view.frame)/12);
[Segcontrol addTarget:Segcontrol action:@selector(segtap:) forControlEvents:UIControlEventValueChanged];
[Segcontrol setSelectedSegmentIndex:0];
[Segcontrol setTintColor:[UIColor blueColor]];
Segcontrol.layer.cornerRadius=5;
[self.view addSubview:Segcontrol];
-(void)segtap:(id)sender{
if (Segcontrol.selectedSegmentIndex==0) {
self.view.backgroundColor=[UIColor blueColor];
}else if (Segcontrol.selectedSegmentIndex==1){
self.view.backgroundColor=[UIColor redColor];
}
}
You are adding the SegmentControl
object Segcontrol
as target to the segment action. Rather than this the object self
should be added as target. Change the code like below and you are good to go.
[Segcontrol addTarget:self action:@selector(segtap:) forControlEvents:UIControlEventValueChanged];
Implement segtap method like this.
-(void)segtap:(id)sender
{
switch (Segcontrol.selectedSegmentIndex)
{
case 0:
NSLog(@"Index 0 selected");
break;
case 1:
NSLog(@"Index 1 selected");
break;
}
}
I think you might be forgotten to pass argument to the method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.