如何进行这样的分段控制

时间:2014-09-12 08:21:59

标签: ios objective-c iphone ipad uisegmentedcontrol

今天我创建了一个自定义分段控件。对照的外观如下:

enter image description here

我尝试了两种方法:

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

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

然而,这是我得到的结果:
enter image description here

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

2 个答案:

答案 0 :(得分:2)

我一直觉得自定义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];
        }

    }
}

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

答案 1 :(得分:0)

以下是very good article如何进行自定义分段控制 看起来你已经尝试过类似的方法,但是你已经搞砸了一些图片(可能你误解了API,所以这篇文章应该为你做的工作)。