0

My UISegmentControl has no borders and segment separators. I want to place a line below the selected segment. I tried doing this :

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];  

This puts a line when I tap the segment. But when I release the tap, line is no more seen. I am using UIControlEventValueChanged as the controlEvent.
How may I achieve this without using third party.

Nitish
  • 13,845
  • 28
  • 135
  • 263
  • You cannot achieve without third party, but i suggest you use button and imageview for line. animate the imageview under the button using uiview animation. this is the best and simple way. – Vasanthan Prem May 04 '16 at 09:40

2 Answers2

0

UISegmentedControl is a class that inherits from UIView so you can add/remove subviews to it. So instead of CALayer I would recommend using a UIView or UIImageView to place the line underneath.

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];  

Instantiate your subviews globally so you can remove them or change it's opacity (i.e. bottomView.alpha = 0) at UIControlEventValueChanged,

Pau Senabre
  • 4,155
  • 2
  • 27
  • 36
0

You can achieve this by getting selected subview of segment control. Here is sample code put this into viewDidLoad for default selected segment and put in 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];

You can also refer this link may this will help you- https://stackoverflow.com/a/37705692/5097148

Community
  • 1
  • 1
Rohit Khandelwal
  • 1,778
  • 15
  • 23