2011-05-03 4 views
6

셀에 제목 텍스트와 세부 텍스트가있는 것과 비슷한 두 개의 레이블을 넣으려는 UI 단추가 있습니다.여러 레이블이있는 iOS UIButton

기본 텍스트에 대해 더 큰 글꼴을 사용하고 그 아래에 세부 텍스트가 더 작은 버튼을 원합니다.

이것이 가능합니까? 단추 하나에 여러 줄을 넣으려고했지만 각 줄마다 다른 텍스트 크기가 있어야합니다. 그래서 titleLabel의 lineBreakMode 및 numberOfLines을 설정해도 실제로 작동하지 않습니다.

답변

6

여기에 우리가 마침내 사용한 코드가 있습니다. 존 왕 (John Wang)의 도움.

제안에 감사드립니다.

// Formats a label to add to a button. Supports multiline buttons 
// Parameters: 
// button - the button to add the label to 
// height - height of the label. usual value is 44 
// offset - the offset from the top of the button 
// labelText - the text for the label 
// color - color of the text 
// formatAsBold - YES = bold NO = normal weight 
// tagNumber - tag for the label 

- (void) formatLabelForButton: (UIButton *) button withHeight: (double) height andVerticalOffset: (double) offset andText: (NSString *) labelText withFontSize: (double) fontSize withFontColor: (UIColor *) color andBoldFont:(BOOL) formatAsBold withTag: (NSInteger) tagNumber { 

    // Get width of button 
    double buttonWidth= button.frame.size.width; 

    // Initialize buttonLabel 
    UILabel *buttonLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, offset, buttonWidth, height)]; 

    // Set font size and weight of label 
    if (formatAsBold) { 
     buttonLabel.font = [UIFont boldSystemFontOfSize:fontSize]; 
    } 
    else { 
     buttonLabel.font = [UIFont systemFontOfSize:fontSize]; 
    } 

    // set font color of label 
    buttonLabel.textColor = color; 

    // Set background color, text, tag, and font 
    buttonLabel.backgroundColor = [UIColor clearColor]; 
    buttonLabel.text = labelText; 
    buttonLabel.tag = tagNumber; 

    // Center label 
    buttonLabel.textAlignment = UITextAlignmentCenter; 

    // Add label to button 
    [button addSubview:buttonLabel]; 

    [buttonLabel autorelease]; 
} // End formatLabelForButton 
4

내가 추천하는 트릭은 UILabels 상단에 투명 내부가있는 UIButton을 배치하는 것입니다. 나는이 트릭을 전에 사용했지만, 유지 보수와 i18n 측면에서 몇 가지 문제가있을 수 있지만, 매력처럼 작동합니다.

위의 제안 사항을 사용한 5 분 샘플입니다. Label behind button

더 많은 시간이 주어지면 둥근 모서리로 더 좋은 레이블을 만들 수 있습니다.

+0

제안 해 주셔서 감사합니다.하지만 버튼의 배경이있는보기를 만들어야하고 이상적인 두 가지 글꼴 스타일이 필요합니다. – orangemako

+0

@Orangemako @Gordon 제안을 사용하면 레이블 배경에 다른 색상을 지정하십시오. –

1

하위 뷰를 추가 할 수 있어야합니다. 모든 것이 뷰이므로 모든 것이 잠재적으로 하위 뷰를 가질 수 있습니다.

하위 클래스로 하위 클래스를 만들고 하위 클래스 내에 레이블을 넣으면 텍스트 및 하위 텍스트의 속성을 확장하여 값을 변경할 수 있습니다.

100 % 작동 할 수있는 것은 아닙니다. 하지만 내 머리 꼭대기에서 떨어져. UIView는 서브 뷰를 가질 수 있습니다.

관련 문제