2015-02-11 79 views
0

我將UILabel作爲customViewUIBarButtonItem。但是,我需要按鈕寬度是動態的以適應更長的標籤。目前它只是截斷它們。這是我的代碼:伸展UIBarButtonItem容納自定義視圖

let participantCountLabel = UILabel() 
participantCountLabel.text = "\(participantCount) participants" 
self.toolbarLeftButton.customView = participantCountLabel 

我認爲這可能是因爲靈活空間。這是否需要調整大小?

截圖:

screenshot

這是故事板:

enter image description here

回答

0

也許你可以這樣做:

let participantCountLabel = UILabel() 
participantCountLabel.text = "\(participantCount) participants" 
self.toolbarLeftButton.customView = participantCountLabel 
self.toolbarLeftButton.customView.sizeToFit() 
0

嘗試這種方式找到的寬度和文本的高度然後設置標籤尺寸

var participantCountLabel: UILabel=UILabel(frame: CGRectMake(100, 100, 10, 40)); 
    participantCountLabel.text = "\(participantCount) participants" 


    var strText:NSString=participantCountLabel.text! 

    let styleLineBreakWordWrap : NSMutableParagraphStyle=NSMutableParagraphStyle() 
    styleLineBreakWordWrap.lineBreakMode=NSLineBreakMode.ByWordWrapping 
    styleLineBreakWordWrap.alignment=NSTextAlignment.Left 


    var attributes:NSDictionary=[NSFontAttributeName : participantCountLabel.font, 
     NSParagraphStyleAttributeName:styleLineBreakWordWrap] 

    strText.sizeWithAttributes(attributes); 

    var maximumLabelSize : CGSize=CGSizeMake(1000, 100) 

    var textRect: CGRect=strText.boundingRectWithSize(maximumLabelSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil) 

    participantCountLabel.frame.size=textRect.size; 

    self.toolbarLeftButton.customView = participantCountLabel 
相關問題