使用2个UIButtons模拟UISegmentedControl

时间:2014-11-10 23:05:26

标签: ios objective-c uibutton uisegmentedcontrol

我想有两个自定义按钮来模拟UISegmentedControl的行为(切换按钮文字颜色和图像)

这是我到目前为止所做的:

    - (IBAction)byDateTapped:(UIButton *)sender {

    UIColor *darkColor = [UIColor colorWithRed:52/255 green:91/255 blue:120/255 alpha:1.0];
    UIColor *lightColor = [UIColor colorWithRed:158/255 green:200/255 blue:217/255 alpha:1.0];

    self.byDateView.hidden = NO;
    [self.byDateButton setBackgroundImage:[UIImage imageNamed:@"radioOn"] forState:UIControlStateNormal];
    [self.byDateButton setTitleColor:darkColor forState:UIControlStateNormal];
    [self.byDateButton setTitleColor:darkColor forState:UIControlStateHighlighted];

    self.byCategoryView.hidden = YES;
    [self.byCategoryButton setBackgroundImage:[UIImage imageNamed:@"radioOff"]forState:UIControlStateNormal];
    [self.byCategoryButton setTitleColor:lightColor forState:UIControlStateNormal];
    [self.byCategoryButton setTitleColor:lightColor forState:UIControlStateHighlighted];

}

- (IBAction)byCategoryTapped:(UIButton *)sender {

    UIColor *darkColor = [UIColor colorWithRed:52/255 green:91/255 blue:120/255 alpha:1.0];
    UIColor *lightColor = [UIColor colorWithRed:158/255 green:200/255 blue:217/255 alpha:1.0];

    self.byDateView.hidden = YES;
    [self.byDateButton setBackgroundImage:[UIImage imageNamed:@"radioOff"] forState:UIControlStateNormal];
    [self.byDateButton setTitleColor:lightColor forState:UIControlStateNormal];
    [self.byDateButton setTitleColor:lightColor forState:UIControlStateHighlighted];

    self.byCategoryView.hidden = NO;
    [self.byCategoryButton setBackgroundImage:[UIImage imageNamed:@"radioOn"]forState:UIControlStateNormal];
    [self.byCategoryButton setTitleColor:darkColor forState:UIControlStateNormal];
    [self.byCategoryButton setTitleColor:darkColor forState:UIControlStateHighlighted];

}

我唯一能够开始工作的是改变按钮文字颜色。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您的IBAction方法应该像

一样简单

- (IBAction)byDateTapped:(UIButton *)sender {

[self.byDateButton setSelected:YES];
[self.byCategoryButton setSelected:NO];

}

- (IBAction)byCategoryTapped:(UIButton *)sender {

[self.byDateButton setSelected:NO];
[self.byCategoryButton setSelected:YES];

}

您应该对初始化代码(viewDidLoad)上的所有状态进行所有设置。

而不是UIControlStateHighlighted,您应该使用UIControlStateSelected代替[_byDateButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; [_byDateButton setTitleColor:[UIColor greenColor] forState:UIControlStateSelected]; [_byCategoryButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; [_byCategoryButton setTitleColor:[UIColor greenColor] forState:UIControlStateSelected]; 。仅供参考,你也可以为背景图片做同样的事情。

例如:

{{1}}