2020-4-29 解决在iOS11,UISegmentedCo

2020-04-29  本文已影响0人  小专注

问题:

UISegmentedControl中 无论如何调整控件的宽度,文本都显示不全.

解决方案:

1.新建一个Controller 继承UISegmentedControl.重写initWithItems 与  layoutSubviews 方法

1-1 重写initWithItems方法

-(instancetype)initWithItems:(NSArray *)items{

    return [super initWithItems:items];

}

1- 2 主要重新写initWithItems方法

-(void)layoutSubviews{

    [super layoutSubviews];

      for (UIView *subView in self.subviews) {

          for (UIView *subSubview in subView.subviews) {

              if ([subSubview isKindOfClass:[UILabel class]]) {

                  UILabel *label = (UILabel *)subSubview;

                  [label setTranslatesAutoresizingMaskIntoConstraints:NO];

                  NSLayoutConstraint *constraintCenterX = [NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:subView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];

                  [subView addConstraint:constraintCenterX];

                  NSLayoutConstraint *constraintCenterY = [NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:subView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];

                  [subView addConstraint:constraintCenterY];

                  NSLayoutConstraint *constraintWidth = [NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:subView attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0];

                  [subView addConstraint:constraintWidth];

              }

          }

      }

}

2.导入类名 替换UISegmentedController

上一篇下一篇

猜你喜欢

热点阅读