UISegmentedControl with Image and Title

后端 未结 6 2215
滥情空心
滥情空心 2020-12-15 13:45

I am using a UISegmentedControl inside a UIToolBar as button. I can\'t use a normal UIButtonBarItem, because I need to set the t

6条回答
  •  隐瞒了意图╮
    2020-12-15 14:35

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

提交回复
热议问题