今天,我正在创建一个自定义的分段控件。控件的外观如下:

我尝试了两种方法:

- (void)setBackgroundImage:(UIImage *)backgroundImage
                  forState:(UIControlState)state
                barMetrics:(UIBarMetrics)barMetrics

- (void)setDividerImage:(UIImage *)dividerImage
    forLeftSegmentState:(UIControlState)leftState
      rightSegmentState:(UIControlState)rightState
             barMetrics:(UIBarMetrics)barMetrics

但是,这是我得到的结果:

我从设计中提取了边框图像和分隔线(垂直线),但结果看起来很糟糕。如果您有任何想法,请帮助我。

最佳答案

我一直发现定制UISegmentedControl的工作量很大,而且它并不是完全可定制的。
我建议您创建一个继承3个按钮的自定义UIView。它们是完全可定制和完全可控制的:

#define BASE_TAG 123

NSArray *titles = [NSArray arrayWithObjects:@"MAP", @"LOCATIONS", @"BUS", nil];

double y = 0.0;
double x = 0.0;
double width = (frame.size.width / [titles count]);
double height = frame.size.height;

for (int i = 0; i < [titles count]; i++)
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(x, y, width, height)];
    [button.titleLabel setTextAlignment:NSTextAlignmentCenter];
    [button setBackgroundColor:[UIColor clearColor]];
    [button setTag:(BASE_TAG + ([titles count] - i - 1))];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_buttons addObject:button];

    x += width;
}

这是您的按钮操作。在这里单击的按钮将被选中,而所有其他按钮均未选中:
- (void)buttonAction:(id)sender
{
    UIButton *button = (UIButton *)sender;

    NSInteger index = 0;

    for (UIButton *btn in self.subviews)
    {
        if (btn == button)
        {
            index = (btn.tag - BASE_TAG);
            [btn setBackgroundColor:[UIColor colorFromHexString:@"#5ac8f5" alpha:1.0]];
            [btn setSelected:YES];
        }
        else
        {
            [btn setBackgroundColor:[UIColor clearColor]];
            [btn setSelected:NO];
        }
    }

    /* Trigger a delegate here if you like
    if ([_delegate respondsToSelector:@selector(didSelectedIndex:)])
    {
        [_delegate didSelectedIndex:index];
    }
    */
}

这使您可以预先设置选定的索引:
- (void)setSelectedIndex:(NSInteger)index
{
    for (UIButton *button in self.subviews)
    {
        if (button.tag == (BASE_TAG + index))
        {
            [button setBackgroundColor:[UIColor colorFromHexString:@"#5ac8f5" alpha:1.0]];
            [button setSelected:YES];
        }
        else
        {
            [button setBackgroundColor:[UIColor clearColor]];
            [button setSelected:NO];
        }

    }
}

这只是我从一个旧项目中提取的建议代码。您将必须根据需要对其进行自定义。

10-08 05:32