我有一个表格视图和一个有按钮的自定义单元格。根据我的需要,我有时会设置
1.按钮标题
或
2.没有标题的背景图片
on runtime。问题是我的按钮大小,特别是宽度不会根据标题的文本长度或根据背景图像大小而改变。我尝试过 sizeToFit 和 cell.btnChat.sizeThatFits( backgroundimage.size)但它并没有反映任何变化。
“按钮”条件用于设置标题和图像以设置背景图像。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if blockChatForLogin{
if (chatRespones[indexPath.row].type == "text"){
//Adding rows in table
// let cell:ChatResponseController = self.tbChat.dequeueReusableCell(withIdentifier: "ChatResponseCell") as! ChatResponseController
let cell:CustLabelCell = self.tbChat.dequeueReusableCell(withIdentifier: "CustomLabelCell") as! CustLabelCell
cell.lblTextResponse.text = chatRespones[indexPath.row].value
cell.lblTextResponse.layer.masksToBounds=true
cell.lblTextResponse.layer.cornerRadius=5
return cell
}
else if (chatRespones[indexPath.row].type == "button"){
//Adding rows in table
let cell:CustButtonCell = self.tbChat.dequeueReusableCell(withIdentifier: "CustomButtonCell") as! CustButtonCell
cell.btnChat.setTitle(chatRespones[indexPath.row].value,for: .normal)
cell.btnChat.layer.masksToBounds=true
cell.btnChat.layer.cornerRadius=5
cell.btnChat.layer.borderWidth=2
cell.btnChat.layer.borderColor=UIColor(red:0.18, green:0.61, blue:0.49 ,alpha:1.0).cgColor
cell.delegete = self
return cell
}
else if (chatRespones[indexPath.row].type == "image"){
//Adding rows in table
// let cell:ChatButtonController = self.tbChat.dequeueReusableCell(withIdentifier: "ChatButtonCell") as! ChatButtonController
let cell:CustButtonCell = self.tbChat.dequeueReusableCell(withIdentifier: "CustomButtonCell") as! CustButtonCell
if let image: UIImage = UIImage(named:"\(chatRespones[indexPath.row].value.replacingOccurrences(of: ":", with: "")).jpg")
{
cell.btnChat.setImage(image, for: .normal)
cell.btnChat.setTitle("",for: .normal)
cell.btnChat.backgroundColor = UIColor.clear
}
else{
cell.btnChat.backgroundColor = UIColor.clear
cell.btnChat.setTitleColor(UIColor.red, for: .normal)
cell.btnChat.setTitle("Error: Image Missing with name \(chatRespones[indexPath.row].value)",for: .normal)
}
cell.btnChat.layer.masksToBounds=true
cell.btnChat.layer.cornerRadius=5
cell.btnChat.layer.borderWidth=2
cell.btnChat.layer.borderColor=UIColor(red:0.18, green:0.61, blue:0.49 ,alpha:1.0).cgColor
cell.delegete = self
return cell
}
}
default:
print("No case")
}
}
答案 0 :(得分:0)
设置单元格的文本后,您可以执行以下操作:
cell.textLabel.intrinsicContentWidth
要获得所需的文本宽度,可以使用检索到的大小作为宽度创建视图的框架。如果在故事板中设置了任何固定宽度,请小心,因此最好以编程方式创建textLabel。