美文网首页
2019-12-06

2019-12-06

作者: 大神工程师 | 来源:发表于2019-12-06 10:14 被阅读0次

如何适配  iOS 13中UISegmentedControl的颜色?

可以写个UISegmentedControl+ChangeColor的类别。来进行iOS13的颜色样式适配。.

.h文件

#import<Foundation/Foundation.h>

@interface UISegmentedControl (ChangeColor)

- (void)ensureiOS12Style;

@end

.m文件

#import "UISegmentedControl+ChangeColor.h"

@implementation UISegmentedControl (ChangeColor)

- (void)ensureiOS12Style {

    // UISegmentedControl has changed in iOS 13 and setting the tint

    // color now has no effect.

    if(@available(iOS13, *)) {

        UIColor*tintColor = [selftintColor];

        UIImage*tintColorImage = [selfimageWithColor:tintColor];

        // Must set the background image for normal to something (even clear) else the rest won't work

        [self setBackgroundImage:[self imageWithColor:self.backgroundColor ? self.backgroundColor : [UIColor clearColor]] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

        [self setBackgroundImage:tintColorImage forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];

        [self setBackgroundImage:[self imageWithColor:[tintColor colorWithAlphaComponent:0.2]] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];

        [self setBackgroundImage:tintColorImage forState:UIControlStateSelected|UIControlStateSelected barMetrics:UIBarMetricsDefault];

        [self setTitleTextAttributes:@{NSForegroundColorAttributeName: tintColor, NSFontAttributeName: [UIFont boldSystemFontOfSize:14.0f]} forState:UIControlStateNormal];

         [self setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor], NSFontAttributeName: [UIFont boldSystemFontOfSize:14.0f]} forState:UIControlStateSelected];

        [self setDividerImage:tintColorImage forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

        self.layer.borderWidth = 1;

        self.layer.borderColor= [tintColorCGColor];

    }

}

- (UIImage*)imageWithColor: (UIColor*)color {

    CGRectrect =CGRectMake(0.0f,0.0f,1.0f,1.0f);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);

    CGContextFillRect(context, rect);

    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    returntheImage;

}

@end

这样写就OK了,就可以实现之前默认的segmentControl选中时候的字体白色的颜色了。

相关文章

网友评论

      本文标题:2019-12-06

      本文链接:https://www.haomeiwen.com/subject/odmsgctx.html