You can do it:
add category for UIImage:
in UIImage+UISegmentIconAndText.h
@interface UIImage (UISegmentIconAndText)
+ (id) imageFromImage:(UIImage*)image string:(NSString*)string color:(UIColor*)color;
+ (id) imageFromImage:(UIImage*)image string:(NSString*)string color:(UIColor*)color position:(NSString*)position;
@end
in UIImage+UISegmentIconAndText.m
#import "UIImage+UISegmentIconAndText.h"
@implementation UIImage (UISegmentIconAndText)
+ (id) imageFromImage:(UIImage*)image string:(NSString*)string color:(UIColor*)color
{
UIFont *font = [UIFont systemFontOfSize:16.0];
CGSize expectedTextSize = [string sizeWithAttributes:@{NSFontAttributeName: font}];
int width = expectedTextSize.width + image.size.width + 5;
int height = MAX(expectedTextSize.height, image.size.width);
CGSize size = CGSizeMake((float)width, (float)height);
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, color.CGColor);
int fontTopPosition = (height - expectedTextSize.height) / 2;
CGPoint textPoint = CGPointMake(image.size.width + 5, fontTopPosition);
[string drawAtPoint:textPoint withAttributes:@{NSFontAttributeName: font}];
// Images upside down so flip them
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, size.height);
CGContextConcatCTM(context, flipVertical);
CGContextDrawImage(context, (CGRect){ {0, (height - image.size.height) / 2}, {image.size.width, image.size.height} }, [image CGImage]);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
@end
in your code implement Segment:
UIImage *imageWithText = [UIImage imageFromImage:[UIImage imageNamed:@"images/jobaids_tab_icon"] string:@"Hello", nil) color:[UIColor whiteColor]];
[_segmentedController setImage:imageWithText forSegmentAtIndex:0];
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…