UI

iOS13 下自定义 UISegmentedControl的一些

2019-09-27  本文已影响0人  witlee

近日iOS13更新,Xcode也随之升级到11版本,运行了一下项目,发现iOS13针对UISegmentedControl进行了重做,默认样式改成了如下图:


UISegmentedControl.png

这样子之前自定义的UISegmentedControl样式都出现了问题。。。
首先发现圆角设置失效了,iOS12以前设置圆角:

testSegmentedControl.layer.masksToBounds = true
testSegmentedControl.layer.cornerRadius = 10

但是iOS13系统下,完全不起作用,后来找到了方法,可以用重写UISegmentedControl的layoutSubviews方法来设置圆角。

class TestSegmentedControl: UISegmentedControl {

    open override func layoutSubviews() {
        super.layoutSubviews()
        layer.cornerRadius = 10
    }

}

这样子我们用TestSegmentedControl作为子类重写父类的layoutSubviews的方法,就又可以设置圆角啦。

如果项目有需求一定要在iOS13系统上实现iOS12以前的风格样式,可以自定义一个category来实现:(下面是本人在网上找到的方法,亲测有效)

@interface UISegmentedControl (Style_OC)

/// UISegmentedControl 将iOS13风格转化成iOS12之前的风格样式
- (void)ensureiOS12Style;
@end
@implementation UISegmentedControl (Style_OC)
- (void)ensureiOS12Style {
    // UISegmentedControl has changed in iOS 13 and setting the tint
    // color now has no effect.
    if (@available(iOS 13, *)) {
        UIColor *tintColor = [self tintColor];
        UIImage *tintColorImage = [self imageWithColor: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 systemFontOfSize:13]} forState:UIControlStateNormal];
        [self setDividerImage:tintColorImage forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
        self.layer.masksToBounds = YES;
        self.layer.borderWidth = 1;
        self.layer.borderColor = [tintColor CGColor];
       
        
    }
}

- (UIImage *)imageWithColor: (UIColor *)color {
    CGRect rect = 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();
    return theImage;
}
@end

以下是本人项目在iOS13下运行的结果:


自定义样式.png

完美还原!!!

上一篇下一篇

猜你喜欢

热点阅读