Closed cannyboy closed 11 years ago
It would be a welcomed feature yes.
OK, i managed a hacky version with the Example.
Within the nib, I placed the segmented control within a scrollview, which is the same size as the seg control. Made the scrollview a property. I changed this method in the ViewController:
- (IBAction)addSegment:(id)sender
{
[self.segmentedControl insertSegmentWithTitle:@"New" atIndex:0 animated:YES];
if ([self.segmentedControl numberOfSegments] > 5)
{
[self.scrollView setContentSize:CGSizeMake([self.segmentedControl numberOfSegments]*75, self.scrollView.frame.size.height)];
}
[self updateSelectedSegmentLabel];
}
And changed layoutSubviews in SDSegmentedControl:
- (void)layoutSubviews
{
if ([self numberOfSegments]>5)
{
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, 75*[self numberOfSegments], self.frame.size.height);
}
[self layoutSegments];
}
This will only work if you turn off AutoLayout in the nib.
For reasons why, you can give yourself a headache by reading this: http://developer.apple.com/library/ios/#releasenotes/General/RN-iOSSDK-6_0/_index.html#//apple_ref/doc/uid/TP40012166-CH1-SW19
First of all: THANKS FOR A NICE CONTROL! Very easy to get started with and adapt!
I also needed the control to scroll, and this is how I did it.
I also placed it in a scrollview but I needed to know the width for the content size. And my titles is very dynamic, from just a single character to several words...
So in layoutSegment I did this to adjust the frame to the content, making it grow, but not shrink below the default with:
CGRect f = self.frame;
int contWidth = totalItemWidth + (interItemSpace * (self.numberOfSegments+1));
f.size.width = MAX(f.size.width, contWidth);
self.frame = f;
I also needed to reset the width, I always rebuild the array from scratch so I just added this to removeAllSegments:
CGRect frame = self.superview.frame;
frame.size.height = self.frame.size.height;
self.frame = frame;
And to make this work even when not animating the creation, I had to change the following code in insertSegmentWithTitle:
if (animated)
{
[UIView animateWithDuration:.4 animations:^
{
[self layoutSegments];
}];
}
else
{
// [self setNeedsLayout];
// to force recalulation of the frame
[self layoutSegments];
}
Then when I insert the control into a scrollview, or just recreating it, I just need to do:
[scrollview setContentSize:CGSizeMake(SDControl.frame.size.width , SDControl.frame.size.height)];
I don't think we can get the content view to autoadjust to changes, but I'm not sure. I hope this might trigger some ideas for some official scrolling support.
Scrolling is the next feature I'll integrate.
Great, works fine!
Thanks for your great work!
Is there a way to set the buttons within a scroll view, so that more than 4 or 5 items can be added without things getting cramped?
There is a similar library here - https://github.com/MugunthKumar/MKHorizMenuDemo - which has this ability.. but in other ways it is less appealing.