获取adjustsFontSizeToFitWidth以使用舒适内容的约束

时间:2014-05-17 02:20:46

标签: ios objective-c uilabel autolayout nsautolayout

这是一个小小的视图控件我已经编写过来测试我遇到的约束和adjustsFontSizeToFitWidth的问题。它是一个小东西,可以添加标签并从标签中删除单词,以查看label_title中各种内容大小如何影响布局。所需的布局紧贴label_title(label_count占据了房间的其余部分)。不幸的是它还不是很舒服。

以下是3个视图状态我拍摄的屏幕,以说明我试图解决的蓝色标题缺乏贴心感。

接下来是运行此视图的视图控制器的完整源代码。

one word - pretty snug

two words - not snug at all

three words - pretty snug

#import "MainViewController.h"

@interface MainViewController ()

// stuff to test our problem with
@property(nonatomic,strong) UIButton * addButton;
@property(nonatomic,strong) UIButton * removeButton;

// our problem
@property(nonatomic,strong) UIView * view_labels;
@property(nonatomic,strong) UILabel * label_title;
@property(nonatomic,strong) UILabel * label_count;

@end

@implementation MainViewController

// synthesize for the views constraint mapping
@synthesize label_title;
@synthesize label_count;

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.view setBackgroundColor:[UIColor grayColor]];

    self.addButton = [self buttonWithTitle:@"Add Word"
                                  selector:@selector(addButtonPressed) color:[UIColor greenColor]];
    self.removeButton = [self buttonWithTitle:@"Remove Word"
                                     selector:@selector(removeButtonPressed) color:[UIColor redColor]];

    // view containing our troublesome labels
    self.view_labels = [[UIView alloc] init];
    [self.view addSubview:self.view_labels];
    //[self.view_labels setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view_labels setBackgroundColor:[UIColor lightGrayColor]];

    // label row 1
    self.label_title = [self labelWithText:@"word" defaultFontSize:30.0 bgcolor:[UIColor blueColor]];
    [self.view_labels addSubview:self.label_title];

    // label row 2
    self.label_count = [self labelWithText:@"77" defaultFontSize:40.0 bgcolor:[UIColor purpleColor]];
    [self.view_labels addSubview:self.label_count];


    NSDictionary *views = NSDictionaryOfVariableBindings(label_title, label_count);
    NSDictionary *metrics = @{@"pad":@2};

    [self.view addConstraints:[NSLayoutConstraint
                               constraintsWithVisualFormat:@"V:|-(==pad)-[label_title(<=44)]-(==pad)-[label_count]-(==pad)-|"
                               options:0
                               metrics:metrics
                               views:views]];
    [self.view addConstraints:[NSLayoutConstraint
                               constraintsWithVisualFormat:@"|-(==pad)-[label_title]-(==pad)-|"
                               options:0
                               metrics:metrics
                               views:views]];
    [self.view addConstraints:[NSLayoutConstraint
                               constraintsWithVisualFormat:@"|-(==pad)-[label_count]-(==pad)-|"
                               options:0
                               metrics:metrics
                               views:views]];
}

#pragma mark - boiler plate stuff

-(UILabel*) labelWithText:(NSString*) text defaultFontSize:(float) fontSize bgcolor:(UIColor*) color
{
    UILabel * label = [[UILabel alloc] init];
    [label setTranslatesAutoresizingMaskIntoConstraints:NO];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setTextColor:[UIColor whiteColor]];
    [label setAdjustsFontSizeToFitWidth:YES];
    [label setNumberOfLines:0];
    [label setMinimumScaleFactor:0.6];
    [label setFont:[UIFont boldSystemFontOfSize:fontSize]];
    [label setBackgroundColor:color];
    [label setText:text];
    return label;
}

-(UIButton*) buttonWithTitle:(NSString*) title selector:(SEL) selector color:(UIColor*) color
{
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:button];
    [button setTitle:title forState:UIControlStateNormal];
    [button setBackgroundColor:color];
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    return button;
}

-(void) viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];

    float SQUARE_SIZE = 100;

    [self.addButton setFrame:CGRectMake(0, self.view.frame.size.height-44.0, self.view.frame.size.width, 44.0)];
    [self.removeButton setFrame:CGRectMake(0, self.view.frame.size.height-(44.0*2), self.view.frame.size.width, 44.0)];

    [self.view_labels setFrame:CGRectMake(SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)];
}

-(void) addButtonPressed
{
    NSString * text = self.label_title.text;
    if (text == nil){
        text = @"";
    }
    text = [NSString stringWithFormat:@"%@%@",text,@" word"];
    text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [self.label_title setText:text];
}

-(void) removeButtonPressed
{
    NSString * text = self.label_title.text;
    if (text == nil || [text isEqualToString:@""]){
        return;
    }
    NSArray * array = [text componentsSeparatedByString:@" "];
    text = @"";
    for (int i = 0; i < [array count]-1; i++){
        NSString * token = [array objectAtIndex:i];
        text = [NSString stringWithFormat:@"%@ %@",text,token];
    }
    text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [self.label_title setText:text];
}

@end

1 个答案:

答案 0 :(得分:0)

如果您尝试在UILabel中插入文本,请通过以下方法替换您的方法。

-(UILabel*)labelWithText:(NSString*) text defaultFontSize:(float) fontSize bgcolor:(UIColor*) color
{
@autoreleasepool {
   UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50,100,100)];
   [label setTextAlignment:NSTextAlignmentCenter];
   [label setTextColor:[UIColor whiteColor]];

  [label setAdjustsFontSizeToFitWidth:YES];
  [label setFont:[UIFont boldSystemFontOfSize:fontSize]];
  [label setBackgroundColor:color];
  [label setText:text];
  [label setNumberOfLines:0];

    while (fontSize > 0.0)
    {
      CGSize size = [text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, label.frame.size.height) lineBreakMode:NSLineBreakByWordWrapping];

        if (size.height <= label.frame.size.height)
        break;

      fontSize -= 1.0;
     }
  [label setFont:[UIFont boldSystemFontOfSize:fontSize]];
  return label;
 }
}