允许选择3个UIButtons中的1个

时间:2012-12-04 18:31:44

标签: iphone objective-c ios

我正在创建一个应用,我在屏幕上有三个按钮。必须始终选择其中一个按钮。当应用程序加载时,第一个按钮被设置为选中,并执行其操作。当用户按下另一个按钮时,取消选择当前按钮并选择新按钮。

我对Objective-C有点新鲜。这就是我提出的,但没有一个我期待的工作。 我在标题中设置了按钮插座。



    - (IBAction)buttonSelector:(id)sender
    {
        firstButton.selected = YES;
        secondButton.selected = NO;
        thirdButton.selected = NO;

        if (firstButton.selected = YES)
        {
            [firstbutton setBackgroundImage:[UIImage imageNamed:"selected.png"]];
            secondButton.selected = NO;
            [secondButton setBackgroundImage:[UIImage imageNamed:"un_selected.png"]];
            thirdButton.selected = YES;
            [thirdButton setBackgroundImage:[UIImage imageNamed:"un_selected.png"]];
        } else if (secondButton.selected = YES)
        {
            [secondButton setBackgroundImage:[UIImage imageNamed:"selected.png"]];
            firstButton.selected = NO;
            [firstButton setBackgroundImage:[UIImage imageNamed:"un_selected.png"]];
            thirdButton.selected = NO;
            [firstButton setBackgroundImage:[UIImage imageNamed:"un_selected.png"]];
        } else if (thirdButton.selected = YES)
        {
            [thirdButton setBackgroundImage:[UIImage imageNamed:"selected.png"]];
            firstButton.selected = NO;
            [firstButton setBackgroundImage:[UIImage imageNamed:"un_selected.png"]];
            secondButton.selected = NO;
            [secondButton setBackgroundImage:[UIImage imageNamed:"un_selected.png"]];
        } else {
            [sender setBackgroundImage:[UIImage imageNamed:"un_selected.png"]];
        }

    }

修改1:

我尝试了UISegmentedControl,但似乎无法为我正在寻找的内容进行足够的自定义。理想情况下,按钮将更多沿着这些线:  http://i.stack.imgur.com/LPwoR.jpg

按钮将有一个将改变的背景图像

2 个答案:

答案 0 :(得分:5)

您应该使用UISegmentControl。这是您正在寻找的确切功能。这是apple documentation on this

Here is a tutorial from Ray wenderlich关于如何自定义包含UISegmentControl

的UI元素

例如: -

NSArray *itemArray = [NSArray arrayWithObjects: @"One", @"Two", @"Three", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(35, 200, 250, 50);
segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;

答案 1 :(得分:0)

只需使用for循环执行此任务,首先只需将图像设置为所有按钮,然后更改所选图像的图像。