Ios 如何制作这样的分段控件
今天我要创建一个自定义分段控件。控件的外观如下所示: 我尝试了两种方法:Ios 如何制作这样的分段控件,ios,objective-c,iphone,ipad,uisegmentedcontrol,Ios,Objective C,Iphone,Ipad,Uisegmentedcontrol,今天我要创建一个自定义分段控件。控件的外观如下所示: 我尝试了两种方法: - (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics - (void)setDividerImage:(UIImage *)dividerImage
- (void)setBackgroundImage:(UIImage *)backgroundImage
forState:(UIControlState)state
barMetrics:(UIBarMetrics)barMetrics
- (void)setDividerImage:(UIImage *)dividerImage
forLeftSegmentState:(UIControlState)leftState
rightSegmentState:(UIControlState)rightState
barMetrics:(UIBarMetrics)barMetrics
然而,我得到的结果是:我从设计中提取了边界图像和分隔线(垂直线),但结果看起来很糟糕。如果您有任何想法,请帮助我。我总是发现定制
UISegmentedControl
的工作量太大,而且它不是完全可定制的。
我建议您自己创建一个自定义UIView,继承3个按钮。它们是完全可定制和完全可控的:
#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)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];
}
}
}
这只是我从一个旧项目中提取的一个建议代码。您必须根据自己的需要对其进行自定义。以下是如何进行自定义分段控制。看起来您已经尝试过类似的方法,但是您在图像方面弄乱了一些东西(可能您误解了API,因此本文应该为您完成这项工作)。对于了解这一点的初创企业,您可以查看此内容。在那里你可以找到很多定制视图,包括UISegment。所以可能会有帮助。谢谢,我非常喜欢你的解决方案。我就是这么做的。这个解决方案需要的设计技巧对我来说是没有用的。
- (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];
}
}
}