0

我想以編程方式將多個UILabel並排添加到TableViewCell。 UILabels具有不同的寬度。以編程方式並排添加具有不同寬度的UILabels

圖片中的第一個單元格顯示了問題,第二個單元格是我想要做的。

在這個例子中,我想添加四個UILabel到一個TableViewCell。但是TableViewCell的寬度小於UILabels的寬度。因此,我必須增加CellHeight並將UILabels添加到其他UILabels(如圖中的第二個單元格)。

enter image description here

+0

你可以在每個你想要的位置添加標籤。讓label = UILabel(frame:CGRect(x:0,y:0,width:225,height:25))。更改位置 – Gregga17

+0

的x和y但我的問題是標籤有不同的寬度。我如何計算第三個標籤不適合該行? –

+0

視圖的寬度是375.所以一個標籤的寬度是150,另一個是225。第三個標籤放在第一個標籤下面。通過設置y。 – Gregga17

回答

2

你應該把你的UICollectionViewUITableViewCell的一排內。 您的UICollectionView的每個單元格將有多個UILabel。根據您的標籤數量更新您的UICollectionView的dataSource。將isScrollEnabled設置爲UICollectionView,並設置自動行高爲UITableViewCell

此外,設置流佈局UICollectionView

if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSizeMake(1, 1) } 

調整單元格大小象下面這樣:

func collectionView(_ collectionView: UICollectionView, 
         layout collectionViewLayout: UICollectionViewLayout, 
         sizeForItemAt indexPath: IndexPath) -> CGSize { 


     let size: CGSize = keywordArray[indexPath.row].size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14.0)]) 
     return CGSize(width: size.width + 45.0, height: keywordsCollectionView.bounds.size.height) 
    } 
+0

這對於這種情況的矯枉過正以及你將使用什麼樣的UICollectionView佈局。你將如何確定集合視圖中單元格的寬度/高度。你是否建議一個完全自定義的UICollectionView佈局來動態調整自己? –

+0

@UpholderOfTruth答案更新 –

+0

這很有道理,我喜歡它。 –

0

首先,你必須做出的標籤。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell 

     let label1 = UILabel(frame: CGRect(x: 5, y: 5, width: 100, height: 25)) 
     label1.text = "Label 1" 
     let label2 = UILabel(frame: CGRect(x: 110, y: 5, width: 225, height: 25)) 
     label2.text = "Label 2" 
     let label3 = UILabel(frame: CGRect(x: 5, y: 40, width: 100, height: 25)) 
     label3.text = "Label 3" 
     let label4 = UILabel(frame: CGRect(x: 110, y: 40, width: 225, height: 25)) 
     label4.text = "Label 4" 
     cell.addSubview(label1) 
     cell.addSubview(label2) 
     cell.addSubview(label3) 
     cell.addSubview(label4) 

    return cell 
} 

每個標籤都有不同的寬度和不同的位置。你可以用它玩

相關問題