How to resize text (font) to fit in UISegment of UISegmentedControl?

后端 未结 3 1157
后悔当初
后悔当初 2021-01-02 19:15

Is there any way to reduce font size that can be fit in single segment of UISegmentedControl ?

Have tried many thing something like,

[[U         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-02 20:03

    I found the issue, Actually it was my mistake!!! I was setting numberOfLines,adjustsFontSizeToFitWidth,minimumScaleFactor and TitleTextAttributes toghether. If we set titleTextAttribute then minimumScaleFactor can't work.

    Update : (As asked by @HawkEye1194 in comment of another answer)

    I have end up with below solution,

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

    If your not setting title textattribute as above then you can use below code

    // ********** 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];
    
    
            }
        }
    }
    

    You can adjust single segment's size as per it's content by below code,

     //*************** adjust single segment size as per content
    
     segment.apportionsSegmentWidthsByContent = YES;
    

提交回复
热议问题