选择分段控件时如何设置图像而未选择分段控件?

时间:2011-06-29 17:54:45

标签: iphone objective-c

我有3个分段控件,我想在选择第一个分段控件时使用一个图像,而在未选中时使用一个...对其他两个分段控件执行相同操作但显然使用不同的图像。请帮忙!

2 个答案:

答案 0 :(得分:2)

向细分控件添加操作。

[segmentedControl addTarget:self action:@selector(segmentedControlClicked:) forControlEvents:UIControlEventValueChanged];

然后实施segmentedControlClicked:

-(void) segmentedControlClicked:(UISegmentedControl*) segmentedControl
{
    if(segmentedControl.selectedSegmentIndex == 0)
    { 
        NSLog(@"First selected");
    }
    else if(segmentedControl.selectedSegmentIndex == 1)
    {
         NSLog(@"Secondselected");
    }
    else if(segmentedControl.selectedSegmentIndex == 2)
    {
         NSLog(@"third selected"); 
    }
}

答案 1 :(得分:1)

我曾经写过这个类似的问题。也许你可以重用一些。

// Create a segmented control.
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:nil];
[segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"up_button.png"] atIndex:0 animated:YES];
[segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"down_button.png"] atIndex:1 animated:YES];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.frame = CGRectMake(0, 0, 90, 30);
[segmentedControl setMomentary:YES];
[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];

// Check if this is the first and / or the last page in order to enable or disable the back / forward button.
if ([recipesArray count] == 1) {
    [segmentedControl setEnabled:NO forSegmentAtIndex:0];
    [segmentedControl setEnabled:NO forSegmentAtIndex:1];
} else if ([currentIndex intValue] == 0) {
    [segmentedControl setEnabled:NO forSegmentAtIndex:0];
} else if ([currentIndex intValue]+1 == [recipesArray count]) {
    [segmentedControl setEnabled:NO forSegmentAtIndex:1];
}

// Initialize a bar button item with the segmented control as custom view and assign it to the right bar button item.
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
self.navigationItem.rightBarButtonItem = barButtonItem;

[segmentedControl release];