Git Product home page Git Product logo

urbsegmentedcontrol's Introduction

URBSegmentedControl

Overview

URBSegmentedControl is a more flexible alternative to the default UISegmentedControl available in UIKit that offers easier customization and more options for layout orientations with titles and images. However, much of the same functionality and API methods that are available in UISegmentedControl are also available in URBSegmentedControl, making it an easier drop-in replacement within your own projects.

Screenshot of the sample project example

Features

  • Segments can be just icons or titles, or titles with icons
  • Supports customizable colors and fonts
  • Supports using UIAppearance for setting the global styles on all instances
  • Supports blocks for value changes
  • Automatically tints images based on normal and selected image colors (no need for two separate versions of your icons)
  • Horizontal and vertial layout orientations for the overall control and for each individual segment
  • Uses ARC and targets iOS 5.0+

Installation

Installing with CocoaPods

CocoaPods is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries in your projects.

Add the following to your Podfile and run $ pod install:

pod "URBSegmentedControl"

If you don't have CocoaPods installed or integrated into your project, you can learn how to do via CocoaPods.

Installing Manually

  • import URBSegmentedControl.h and URBSegmentedControl.m files into your project, and then include "URBSegmentedControl.h" where needed, or in your precompiled header
  • link against the QuartzCore framework by adding QuartzCore.framework to your project under Build Phases > Link Binary With Libraries.

Once installed, you can then use URBSegmentedControl just as you would with UIKit's UISegmentedControl.

This project uses ARC and targets iOS 5.0+.

Usage

(see more detailed usage examples in the included project under /SampleProject)

The following is the most basic example of creating an URBSegmentedControl instance that mimics the same for UISegmentedControl:

NSArray *titles = [NSArray arrayWithObjects:[@"Item 1" uppercaseString], [@"Item 2" uppercaseString], [@"Item 3" uppercaseString], nil];
URBSegmentedControl *control = [[URBSegmentedControl alloc] initWithItems:titles];
[control addTarget:self action:@selector(handleSelection:) forControlEvents:UIControlEventValueChanged];
[viewController.view addSubview:control];

Instead of adding a target to the control to respond to value changes, you can set a handler block on each instance:

NSArray *titles = [NSArray arrayWithObjects:[@"Item 1" uppercaseString], [@"Item 2" uppercaseString], [@"Item 3" uppercaseString], nil];
URBSegmentedControl *control = [[URBSegmentedControl alloc] initWithItems:titles];
[control setControlEventBlock:^(NSInteger index, URBSegmentedControl *segmentedControl) {
	NSLog(@"control value changed - index=%i", index);
}];
[viewController.view addSubview:control];

If you just want a control with icons only, you would initialize the instance with initWithIcons::

NSArray *icons = [NSArray arrayWithObjects:[UIImage imageNamed:@"mountains.png"], [UIImage imageNamed:@"snowboarder.png"], [UIImage imageNamed:@"biker.png"], nil];
URBSegmentedControl *control = [[URBSegmentedControl alloc] initWithIcons:icons];
[viewController.view addSubview:control];

Alternative, you can initialize an instance with both titles and images (as long as both arrays provided for each are equal in length):

NSArray *titles = [NSArray arrayWithObjects:[@"Item 1" uppercaseString], [@"Item 2" uppercaseString], [@"Item 3" uppercaseString], nil];
NSArray *icons = [NSArray arrayWithObjects:[UIImage imageNamed:@"mountains.png"], [UIImage imageNamed:@"snowboarder.png"], [UIImage imageNamed:@"biker.png"], nil];
URBSegmentedControl *control = [[URBSegmentedControl alloc] initWithTitles:titles icons:icons];
[viewController.view addSubview:control];

Customization

Your URBSegmentedControl can be customized using the following properties:

// base styles
@property (nonatomic, strong) UIColor *baseColor;						// default [UIColor colorWithWhite:0.3 alpha:1.0]
@property (nonatomic, strong) UIColor *strokeColor;						// default [UIColor darkGrayColor]
@property (nonatomic, assign) CGFloat strokeWidth;						// default 2.0
@property (nonatomic) CGFloat cornerRadius;								// default 2.0
@property (nonatomic, assign) UIEdgeInsets segmentEdgeInsets;			// default UIEdgeInsetsMake(4.0, 4.0, 4.0, 4.0)
@property (nonatomic, assign) URBSegmentImagePosition imagePosition;	// default URBSegmentImagePositionLeft

// segment styles
@property (nonatomic, strong) UIColor *segmentBackgroundColor;			// default [UIColor redColor]
@property (nonatomic, strong) UIColor *imageColor;						// default [UIColor grayColor]
@property (nonatomic, strong) UIColor *selectedImageColor;				// default [UIColor whiteColor]
@property (nonatomic, assign) BOOL showsGradient;						// determines if the base and segment background should have a gradient applied, default YES

By default, your images will be tinted with the colors you define using the imageColor and selectedImageColor properties. If you would rather keep your images in their original format, just set these color properties to nil:

control.imageColor = nil;
control.selectedImageColor = nil;

In most cases, the default insets applied to the content, title and image for each segment will work. However, if your control is smaller or you wish to adjust the sizes of elements better, you can adjust the insets by setting the following properties on your instance:

@property (nonatomic, assign) UIEdgeInsets contentEdgeInsets;
@property (nonatomic, assign) UIEdgeInsets titleEdgeInsets;
@property (nonatomic, assign) UIEdgeInsets imageEdgeInsets;

TODO

  • Support setting images to use for background and segment states instead of drawing in CoreGraphics within the class
  • Support for UISegmentedControl's momentary mode - Better support for customization using UIAppearance

Credits

The sample URBSegmentedControlDemo project uses the following icons from their respective authors (all from The Noun Project ):

License

This code is distributed under the terms and conditions of the MIT license. Review the full LICENSE for all the details.

Support/Contact

Think you found a bug or just have a feature request? Just post it as an issue, but make sure to review the existing issues first to avoid duplicates. You can also hit me up at @u10int for anything else, or to let me know how you're using this component. Thanks!

urbsegmentedcontrol's People

Contributors

u10int avatar nowsprinting avatar

Stargazers

 avatar Xiaodingpa avatar Fleeming avatar Orion avatar Kai Li avatar  avatar QRice avatar Nikolaos Papadakis avatar Tony avatar Spark avatar xuaner72 avatar Hanis avatar  avatar Zhu Weicheng avatar Fang avatar  avatar Ronan avatar Yuchen avatar acartagena avatar  avatar Angus H. avatar Allen avatar Dr. Mickey Lauer avatar  avatar Aaron ttgb avatar Koson avatar Max Komarychev avatar heramerom avatar Ehab Abdou avatar Derek Hartley avatar colorbox avatar __weak_Point avatar  avatar wudabei avatar Mikhail Isaev aka iMike avatar  avatar Andy Chentsov avatar ThomasW avatar 李磊 avatar Seçkin Can Şahin avatar Frederic D. avatar Karsten Gresch avatar  avatar  avatar Arn avatar  avatar Tiago Aleluia avatar Kanta A avatar Leafly avatar Jim avatar  avatar  avatar  avatar JonyFang avatar yao2030 avatar Sam Miller avatar Leon Guan avatar Arthur Ariel Sabintsev avatar  avatar  avatar  avatar JinSuh(진서) Kim avatar ibireme's bot avatar  avatar alacom avatar Natapong Thongkamkoon avatar DJ Tarazona avatar Yuan Heng Fan avatar Indrajit Chakrabarty avatar Tatsuya Arai avatar Walter Femiano avatar tangyumeng avatar  avatar Jeff Bailey avatar Jun G S avatar Hanpo(AO) avatar Vaughan Rouesnel avatar achermao@gmail.com avatar shige github avatar 6david9 avatar Empty avatar Ingmar Lemke avatar  avatar  avatar Jibril Gueye avatar Danis Tazetdinov avatar Ortwin Gentz, FutureTap avatar JIANG YI avatar Tsyganov Stanislav avatar Jesly Varghese avatar Anton avatar Luis Chávez avatar  avatar Schinckus Lionel avatar Trần Thanh Vũ avatar gongbin avatar Andrei avatar Douglas Fischer avatar Alessandro Iob avatar Codes avatar

Watchers

 avatar arden avatar Gregory P. Moore, MD avatar  avatar Eddie Espinal avatar Andrew Zeus avatar  avatar ahashp avatar  avatar mayulu avatar Arn avatar James Cloos avatar  avatar 1ychen avatar Robert La Ferla avatar sunny avatar iStenoxx avatar  avatar Ricardo De Val avatar  avatar

urbsegmentedcontrol's Issues

cyclic references

This code in URBSegmentedControl uses a block that refers to self. The problem is that self will be retained.

        [UIView animateWithDuration:0.4 animations:^{
            [self layoutSegments];
        }];

Instead, it should be something like:

        URBSegmentedControl * __weak weakSelf = self;
        [UIView animateWithDuration:0.4 animations:^{
            URBSegmentedControl * strongSelf = weakSelf;
            if (strongSelf) {
                [strongSelf layoutSegments];
            }
        }];

Wrong first item is selected

Implemented the URBSegmentedControl in my code, but in all the objects, the first item is as selected, but the default in my app is to have no option selected initially. Someone has been there and managed to solve? If yes, how did?

Background color settings not working

This is a known bug that I'm currently working on fixing, where several of the customization properties aren't being applied properly. Also, the UIAppearance support isn't fully working either, so this will be resolved soon.

cant select items when height in vertical layout is high

I am doing something like this: (i am repeating elements just for the sake of showing a lot of elements)
NSArray *titles = [NSArray arrayWithObjects:[@"YES" uppercaseString], [@"NO" uppercaseString],[@"YES" uppercaseString], [@"NO" uppercaseString],[@"YES" uppercaseString], [@"NO" uppercaseString],[@"YES" uppercaseString],[@"YES" uppercaseString], nil];

URBSegmentedControl *control = [[URBSegmentedControl alloc] initWithItems:titles];

control.frame = CGRectMake((self.view.frame.size.width/2)-100, 5, 200.0, [titles count]*80);

From element 0 to element 4 i can select without problems.. but 5,6 and 7 its unselectable.. but if i change size from 80 to 40 .. it all works..

I cant find the reason for this !

question about color

when i run this code in iphone6 or latter,the baseColor and strokeColor became white color,like this
2016-05-03 2 15 43

How to fix it?

few issues and clarifications

hi, thanks much for an outstanding goodlooking control...also great its subclassed of UISegCtrl

plz clarify:

We tried to use it with horizontal layoutorient, but segmentviewlayout vertical with both icons and titles, but its having the following issues

  1. the icons are becoming very very tiny like 10x10 in a viewframe of 57x57 - is unusable this way
  2. the icons are fully decolorized - is this expected behaviour - we'd need for the icons to be left alone as they are provided.
  3. also see that the momentary option of UISegCtrl is not supported and it is requiring a selected index

plz let us know what/how can be fixed.
thanks.

Unselected segment contrast

The brightness/contrast of the unselected segment icons is too faint. How can it be made a little brighter or with more contrast?

Deselecting all Items hangs in assertion

* Just saw this might be a duplicate, sorry - newbie failure*

Hi,

just checked out this nice piece of code (thanks !) and ran into an issue.
I rely on the ability to deselect all segments in the segemented control.
For UISegmentedControl this is possible by setting the selectedSegmentIndex to -1.

URBSegmentedControl has some checks in

- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex

that do not allow -1 as a value.

Tried the following change as a quick and dirty hack:

//NSParameterAssert(selectedSegmentIndex < (NSInteger)self.items.count && selectedSegmentIndex >= 0);
    //20130326 OGGERSCHUMMER fix for unselected control
    NSParameterAssert(selectedSegmentIndex < (NSInteger)self.items.count && selectedSegmentIndex >= -1);

    // deselect current segment if selected
    if (_selectedSegmentIndex >= 0)
        ((URBSegmentView *)[self segmentAtIndex:_selectedSegmentIndex]).selected = NO;
    if (selectedSegmentIndex>=0){//20130326 OGGERSCHUMMER Handle deselection of everything
        [self segmentAtIndex:selectedSegmentIndex].selected = YES;
    }

...

From what I see this does the trick, but I don´t know your code in detail yet.

Maybe you can check and adjust this.

Cheers,
Oggerschummer

Font size for each segment

I want to set the font size for each segment but there is no method to do it nor is there a way to get a segment (item) or list of segments (items).

Analyze result: Array element cannot be nil

XCode "analyze" complains of API misuse (array element cannot be nil) in the method (UIImage *)selectedBackgroundImage

NSArray *segmentGradientColors = @[(id)segmentGradientTopColor.CGColor, (id)segmentGradientBottomColor.CGColor];

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.