2014-05-17 3 views
1

이것은 제약 조건 및 adjustSontToFitWidth가있는 문제를 테스트하기 위해 작성한 작은 뷰 컨트롤입니다. label_title의 다양한 콘텐츠 크기가 레이아웃에 미치는 영향을 확인하기 위해 라벨에서 단어를 추가하고 제거하는 방법이 있습니다. 원하는 레이아웃이 label_title 주변에 잘 어울립니다 (label_count가 나머지 공간을 차지함). 불행히도 아직 아늑한 것은 아닙니다.adjustsFontSizeToFitWidth가 적당한 크기의 컨텍스트에서 작동하도록

다음은 내가 고치려고하는 파란색 제목에 깔끔함이 없음을 보여주기 위해 캡처 한 화면입니다.

다음은이보기를 실행할보기 컨트롤러의 전체 소스입니다. 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 
+0

좀 더 자세히 설명해 주시겠습니까? 나는 위의 질문/진술에서 당신의 문제를 얻지 못했습니다. –

+1

나는 @AnilKumar에 동의한다. Aargh와 스퍼터링 대신에, 당신이 정말로하려고하는 것을 어딘가에 설명하는 것이 어떨까? 예를 들어 텍스트에 맞게 크기를 조정하는 레이블을 만들려고 시도하는 중입니까? 그렇다면 잘 알려진 잘 해결 된 문제입니다. – matt

+0

@AnilKumar 필자는 내 질문과 내가 View Controller의 완전한 소스를 가지고있는 문제를 완전히 다시 말했습니다. 어떤 도움이라도 대단히 감사하겠습니다. –

답변

0

two words - not snug at all

one word - pretty snug

다음으로 당신의 방법을 대체 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; 
} 
} 
+1

'autoreleasepool'의 이상한 사용 –

+0

@SashaZats 그는 백그라운드 스레드에서 이것을 사용할 것입니다. 그냥 누출되지 않도록하고 싶습니다. – Andy

+2

백그라운드 스레드에서이 메소드를 호출하면 예상대로 작동하지 않을 가능성이 있습니다 –