我为UILabel
添加了customView
作为UIBarButtonItem
。但是,我需要按钮宽度是动态的,以适应更长的标签。目前它只是截断它们。这是我的代码:
let participantCountLabel = UILabel()
participantCountLabel.text = "\(participantCount) participants"
self.toolbarLeftButton.customView = participantCountLabel
我认为可能是因为灵活空间。这需要调整大小吗?
截图:
这是故事板:
答案 0 :(得分:0)
也许你可以这样做:
let participantCountLabel = UILabel()
participantCountLabel.text = "\(participantCount) participants"
self.toolbarLeftButton.customView = participantCountLabel
self.toolbarLeftButton.customView.sizeToFit()
答案 1 :(得分: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