UISegmentControl选定索引的底线

时间:2016-05-04 09:13:47

标签: ios objective-c iphone uisegmentedcontrol

我的UISegmentControl没有边框和细分分隔符。我想在选定的细分下方放置一条线。我试过这样做:

CALayer *bottomLayer = [CALayer layer];
bottomLayer.borderColor = [UIColor blackColor].CGColor;
bottomLayer.borderWidth = 3;

// Calculating frame
CGFloat width            = segment.frame.size.width/segment.numberOfSegments;
CGFloat x                = 0;
CGFloat y                = segment.frame.size.height - 5;
bottomLayer.frame       = CGRectMake(x, y,width, 2);

[bottomLayer setName:@"bottom"];
// Adding selection to segment
[segment.layer addSublayer:bottomLayer];  

当我点按片段时,这会放一条线。但是当我释放水龙头时,不再看到线条。我使用UIControlEventValueChanged作为controlEvent 如何在没有使用第三方的情况下实现

2 个答案:

答案 0 :(得分:0)

UISegmentedControl是一个继承自UIView的类,因此您可以向其添加/删除子视图。因此,我建议使用UIView或UIImageView将线放在下面而不是CALayer。

UIView *bottomView = [[UIView alloc] init];
bottomView.backgroundColor = [UIColor blackColor];

// Calculating frame
CGFloat width            = segment.frame.size.width/segment.numberOfSegments;
CGFloat x                = 0;
CGFloat y                = segment.frame.size.height - 5;
bottomView.frame         = CGRectMake(x, y,width, 2);

// Adding selection to segment
[segment addSubview:bottomView];  

全局实例化您的子视图,以便您可以在bottomView.alpha = 0删除它们或更改它的不透明度(即UIControlEventValueChanged),

答案 1 :(得分:0)

您可以通过subview选择segment control来实现此目的。以下是示例代码,将其放入viewDidLoad默认选定的细分受众群并放入UIControlEventValueChanged -

CALayer *bootomBorder = [CALayer layer];
bootomBorder.backgroundColor = [UIColor greenColor].CGColor;
bootomBorder.frame = CGRectMake(0, userProfileSagmentOutlet.subviews[userProfileSagmentOutlet.selectedSegmentIndex].frame.size.height-1, userProfileSagmentOutlet.frame.size.width/userProfileSagmentOutlet.numberOfSegments-2, 1.0f);
[userProfileSagmentOutlet.subviews[userProfileSagmentOutlet.selectedSegmentIndex].layer addSublayer:bootomBorder];

您也可以参考此链接,这可以帮助您 - https://stackoverflow.com/a/37705692/5097148