UIButton's Title Label Word Wrap with Tail Truncation

前端 未结 8 1342
暖寄归人
暖寄归人 2020-12-24 03:11

I need to enable word wrapping and tail truncation, at the same time, on a UIButton\'s titleLabel. Setting numberOfLines to something more than 0 d

8条回答
  •  盖世英雄少女心
    2020-12-24 03:38

    Try setting the numberOfLines more than 2, and set height also accordingly.

        m_button = [UIButton buttonWithType:UIButtonTypeCustom];
    [m_button setFrame:CGRectMake(isLandscape?20:10, 40, isLandscape?300:250, 40)];
    m_button.titleLabel.font  = [UIFont fontWithName:@"HelveticaNeue" size:17];
    [m_btnDiscoverPoint setTitle:@"Title" forState:UIControlStateNormal];
    CGRect buttonFrame = [m_button frame];
    
    if ([m_button.titleLabel.text length]>0) {
        CGSize suggestedSize = [m_button.titleLabel.text sizeWithFont:[UIFont fontWithName:@"HelveticaNeue" size:17] constrainedToSize:CGSizeMake(FLT_MAX,m_button.frame.size.height) lineBreakMode:UILineBreakModeWordWrap];
    
        if (suggestedSize.width >= self.view.frame.size.width) {
            suggestedSize.width = self.view.frame.size.width-10;
            suggestedSize.height=suggestedSize.height+20;
            m_button.titleLabel.numberOfLines=2;
        }
        else{
            m_button.titleLabel.numberOfLines=1;
        }
    
        buttonFrame.size.width = suggestedSize.width;
    
        [m_button setFrame:buttonFrame];
    }
    [m_button setBackgroundColor:[UIColor clearColor]];
    [m_button addTarget:self action:@selector(btnClickAction) forControlEvents:UIControlEventTouchUpInside];
    

提交回复
热议问题