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

我尝试了两种方法:
- (void)setBackgroundImage:(UIImage *)backgroundImage
forState:(UIControlState)state
barMetrics:(UIBarMetrics)barMetrics
- (void)setDividerImage:(UIImage *)dividerImage
forLeftSegmentState:(UIControlState)leftState
rightSegmentState:(UIControlState)rightState
barMetrics:(UIBarMetrics)barMetrics然而,这是我得到的结果:

我从设计中提取了边框图像和分隔线(垂直线),但效果看起来很差。如果你有任何想法,请帮助我。
发布于 2014-09-12 16:36:05
我总是发现定制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];
}
}
}这只是我从一个旧项目中提取的建议代码。您必须根据自己的需要对其进行自定义。
发布于 2014-09-12 16:41:59
这是一个如何进行自定义分段控制的very good article。
看起来您已经尝试过类似的方法,但是您搞砸了一些图像(可能是您误解了API,所以本文将为您做这项工作)。
https://stackoverflow.com/questions/25803824
复制相似问题