2012-06-06 3 views
1

uibutton에 배경 이미지로 추가 할 이미지가 하나 있습니다. 단추 너비에 맞게 이미지를 늘리고 싶습니다. 사용자가 런타임에 버튼의 제목을 입력합니다. 사용자가 입력 한 텍스트의 너비에 따라 이미지가 늘어납니다. 버튼의 특정 폭 너머에서 버튼은 더 이상 늘어나지 않고 대신 텍스트가 잘립니다. 여기 내 코드가iOS 5에서 텍스트의 길이에 따라 이미지를 늘리십시오.

CGSize suggestedSize = [self.strButtonTitle sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]]; 

NSLog(@"Widht:- %f",suggestedSize.width); 

UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
customButton.frame = CGRectMake(50, 200, 75, 40); 

CGRect frame = customButton.frame; 
frame.size.width = suggestedSize.width; 

if (frame.size.width > 75) { 
    frame.size.width = 75; 
    customButton.frame = frame; 
} 
else { 
    frame.size.width +=5; 
    customButton.frame = frame; 
} 

NSLog(@"Custom button width:- %f",customButton.frame.size.width); 

UIImage *buttonImageNormal = [UIImage imageNamed:BUTTON_IMAGE]; 
UIImage *stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0]; 

[customButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal]; 
[customButton setTitle:self.strButtonTitle forState:UIControlStateNormal]; 
[customButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 
[self.view addSubview:customButton]; 

UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:customButton]; 
self.navigationItem.leftBarButtonItem = barButton; 
[barButton release]; 

내 문제는 사용자가 입력 한 텍스트에 따라 버튼 폭이 증가하지 않는다는 것입니다. 사용자가 ppppp를 입력하면 너비가 75pt까지 증가하지 않고 "pp ... p"가 표시됩니다.

도움이되는 정보는 누구나 환영합니다. 감사.

답변

2

문자열의 너비를 측정하는 데 문제가 있습니다. 아래의 방법으로 문자열의 너비를 측정하고 있습니다.

CGSize suggestedSize = [self.strButtonTitle sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]]; 

여기서 systemFont는 크기가 FONT_SIZE로 사용됩니다.

그러나 customButton 텍스트 라벨에 동일한 글꼴을 설정하지 않습니다. 그것은 아래의 방법으로 수행 할 수 있습니다.

[customButton.titleLabel setFont:[UIFont systemFontOfSize:FONT_SIZE]]; 

희망이 있으면 도움이 될 것입니다.

+0

고맙습니다. – iOSAppDev

관련 문제