如何调整文本(字体)的大小以适应UISegmentedControl的UISegment?

时间:2016-07-22 07:06:46

标签: ios objective-c uilabel uisegmentedcontrol

有没有办法减少适合UISegmentedControl的单个片段的字体大小?

尝试了许多类似的东西,

[[UILabel appearanceWhenContainedIn:[UISegmentedControl class], nil] adjustsFontSizeToFitWidth];

[[UILabel appearanceWhenContainedIn:[UISegmentedControl class], nil] setMinimumScaleFactor:0.5];

 NSArray *arr = segment.subviews;  // segment is UISegmentedControl object

for (int i = 0; i < arr.count; i++) {

    UIView *aSegment = [arr objectAtIndex:i];

    for (UILabel *label in aSegment.subviews) {

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

            UILabel *myLabel = (UILabel *)label;

            [myLabel setNumberOfLines:0];

            label.numberOfLines = 0;
            label.adjustsFontSizeToFitWidth = YES;
            label.minimumScaleFactor = 0.5;
        }



    }
}

能够设置段标签的行数,如

  [[UILabel appearanceWhenContainedIn:[UISegmentedControl class], nil] setNumberOfLines:0];

可以根据内容设置单段大小,例如

  segment.apportionsSegmentWidthsByContent = YES;

但在这种情况下,每个细分受众群都有不同的规模。

我希望保持每个细分受众群的大小相同,并希望缩小适合UISegmentLabel (label) UISegmentedControl minimumscalefactorminimumfontsize或{{adjustsFontSizeToFitWidth的字体大小1}}。包含在UISegmentedControl中时,这些属性不适用于标签。

如果任何人可以帮助实现这一目标,我们将不胜感激!!

提前致谢!!

5 个答案:

答案 0 :(得分:7)

我发现了这个问题,其实这是我的错!我正在设置numberOfLines,adjustsFontSizeToFitWidth,minimumScaleFactorTitleTextAttributes。如果我们设置titleTextAttribute,则minimumScaleFactor无法正常工作。

更新:(正如@ HawkEye1194在另一个回答的评论中所提出的那样)

我最终得到了以下解决方案,

 //this will allow multiple lines in label contained by every segment in segmentedcontroller

[[UILabel appearanceWhenContainedIn:[UISegmentedControl class], nil] setNumberOfLines:0];


UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:option];
segment.frame = CGRectMake(20, 50, self.view.frame.size.width - 40, 50);
segment.tintColor = [UIColor grayColor];
segment.selectedSegmentIndex = 0;
segment.backgroundColor = [UIColor whiteColor];
segment.tag = segmentedControllerBaseTag;


[segment addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];

[segment setTitleTextAttributes:@{NSFontAttributeName :[UIFont fontWithName:@"HelveticaNeue" size:17.0], NSForegroundColorAttributeName : [UIColor darkGrayColor] } forState:UIControlStateNormal];
[segment setTitleTextAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:17.0],NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];

如果你没有设置如上所述的标题textattribute,那么你可以使用下面的代码

// ********** if titletextattributes are not set then below method works ***********

   for(uint i=0;i<[segment subviews].count;i++)
   {
    for(UIView *view in [[[segment subviews] objectAtIndex:i] subviews])
    {
        if([view isKindOfClass:[UILabel class]])
        {

            [(UILabel*)view setNumberOfLines:0];
            [(UILabel*)view setAdjustsFontSizeToFitWidth:YES];
            [(UILabel*)view setMinimumScaleFactor:0.7];


        }
    }
}

您可以按照以下代码调整单段的内容,

 //*************** adjust single segment size as per content

 segment.apportionsSegmentWidthsByContent = YES;

答案 1 :(得分:3)

试试这个,我希望这会对你有帮助,你会知道这是如何运作的 -

我有一个UISegmentedControl,即_userProfileSagmentOutlet有三个段。这是示例代码 -

CGFloat fontSize = 15;

[_userProfileSagmentOutlet setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Roboto-medium" size:fontSize],
                                                    NSForegroundColorAttributeName:[UIColor whiteColor]}
                                         forState:UIControlStateSelected];

[_userProfileSagmentOutlet setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Roboto-medium" size:fontSize],
                                                    NSForegroundColorAttributeName:[UIColor whiteColor]}
                                         forState:UIControlStateNormal];

这是以前的代码截断尾部的标题,如下图 -

enter image description here

这是主要逻辑,它使每个标题适合具有相同字体大小的片段 -

CGFloat fontSize = 15;

NSAttributedString* firstTitle = [[NSAttributedString alloc] initWithString:@"Membership History" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"Roboto-medium" size:fontSize]}];

NSAttributedString* secondTitle = [[NSAttributedString alloc] initWithString:@"Event History" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"Roboto-medium" size:fontSize]}];

NSAttributedString* thirdTitle = [[NSAttributedString alloc] initWithString:@"Booked Classes" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"Roboto-medium" size:fontSize]}];


float maxW=MAX(MAX(firstTitle.size.width, secondTitle.size.width), thirdTitle.size.width);

while (maxW > _userProfileSagmentOutlet.subviews[0].frame.size.width) {

    fontSize--;

    firstTitle = [[NSAttributedString alloc] initWithString:@"Membership History" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"Roboto-medium" size:fontSize]}];

    secondTitle = [[NSAttributedString alloc] initWithString:@"Event History" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"Roboto-medium" size:fontSize]}];

    thirdTitle = [[NSAttributedString alloc] initWithString:@"Booked Classes" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"Roboto-medium" size:fontSize]}];

    maxW=MAX(MAX(firstTitle.size.width, secondTitle.size.width), thirdTitle.size.width);


}
[_userProfileSagmentOutlet setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Roboto-medium" size:fontSize],
                                                    NSForegroundColorAttributeName:[UIColor whiteColor]}
                                         forState:UIControlStateSelected];

[_userProfileSagmentOutlet setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Roboto-medium" size:fontSize],
                                                    NSForegroundColorAttributeName:[UIColor whiteColor]}
                                         forState:UIControlStateNormal];

使用此代码图像后看起来像这样(相同的字体大小和文本适合细分和工作正常) -

enter image description here

如果有人需要,这是Swift扩展 -

    var fontSize:CGFloat = 15.0;

    var firstTitle = NSMutableAttributedString.init(string: "Membership History", attributes:[NSFontAttributeName: UIFont.systemFontOfSize(fontSize)])

    var secondTitle = NSMutableAttributedString.init(string: "Events History" ,attributes:[NSFontAttributeName: UIFont.systemFontOfSize(fontSize)]);

    var thirdTitle = NSMutableAttributedString.init(string: "Booked Classes" ,attributes:[NSFontAttributeName: UIFont.systemFontOfSize(fontSize)]);

    var maxW:CGFloat = max(max(firstTitle.size().width, secondTitle.size().width), thirdTitle.size().width);

    while (maxW > userProfileSagmentOutlet.subviews[0].frame.size.width) {

        fontSize--;

         firstTitle = NSMutableAttributedString.init(string: "Membership History", attributes:[NSFontAttributeName: UIFont.systemFontOfSize(fontSize)])

         secondTitle = NSMutableAttributedString.init(string: "Events History" ,attributes:[NSFontAttributeName: UIFont.systemFontOfSize(fontSize)]);

         thirdTitle = NSMutableAttributedString.init(string: "Booked Classes" ,attributes:[NSFontAttributeName: UIFont.systemFontOfSize(fontSize)]);

         maxW = max(max(firstTitle.size().width, secondTitle.size().width), thirdTitle.size().width);

    }
    userProfileSagmentOutlet.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFontOfSize(fontSize),NSForegroundColorAttributeName:UIColor.whiteColor()], forState:UIControlState.Normal)

    userProfileSagmentOutlet.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFontOfSize(fontSize),NSForegroundColorAttributeName:UIColor.whiteColor()], forState:UIControlState.Selected)

答案 2 :(得分:0)

SWIFT 4

允许标签中包含多行

if #available(iOS 9.0, *) {
    UILabel.appearance(whenContainedInInstancesOf: [UISegmentedControl.self]).numberOfLines = 0
}

答案 3 :(得分:0)

我在视图控制器中运行它,并在 viewDidAppear 之后调用它

func autoshrinkSegmentFontSize() {
    for subview in segments.subviews {
        for label in subview.subviews {
            if let myLabel = subview as? UILabel {
                myLabel.adjustsFontSizeToFitWidth = true
                myLabel.minimumScaleFactor = 0.5
            }
        }
    }
}

答案 4 :(得分:0)

现代 Swift 中最简单的解决方案是

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
        
    _ = Your_UISegmentControl.subviews.compactMap { $0.subviews.compactMap {
        ($0 as? UILabel)?.adjustsFontSizeToFitWidth = true
        ($0 as? UILabel)?.minimumScaleFactor = 0.5
    }}
}