普通 CollectionView 单元格中的动态 CollectionView 单元格
Dynamic CollectionView cell in a normal CollectionView cell
我在 CollectionView 单元格中使用带有 CollectionView 的故事板。我需要里面的一个根据数组中给定的文本调整高度并将其连接到我的 UILabel。
我发布了一个答案,欢迎使用!
这里有一个 snippet 测量字符串的大小。 (您可能需要将默认值 220 更改为适合您需要的值。)
extension String {
func size(width:CGFloat = 220.0, font: UIFont = UIFont.systemFont(ofSize: 17.0, weight: .regular)) -> CGSize {
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = self
label.sizeToFit()
return CGSize(width: label.frame.width, height: label.frame.height)
}
}
在您的 collectionViewController 中,确保您在视图控制器中继承 UICollectionViewDelegateFlowLayout
:
class yourViewController : UICollectionViewController, UICollectionViewDelegateFlowLayout
然后实现sizeForItemAt函数:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let yourString = yourStringArray[indexPath.row]
let padding = CGSize.init(width: 20, height: 20)
let textSize = yourString.size(width: collectionView.frame.width) // you can also specify a font with fontSize and weight. Default is set to the system font with fontSize 17.
return CGSize.init(width: textSize.width + (padding.width / 2), height: textSize.height + (padding.height / 2))
}
注意:我已经在您的单元格 10 的所有边上添加了任意填充,因此您可能需要根据您希望单元格的外观添加填充。 'size' 仅根据文本测量标签的大小。
这正是我一直在寻找的...但任何人都可以随意将它与您的故事板 collectionView 一起使用。
您的 collectionView 所在位置:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var CV: UICollectionView!
let screenSize: CGRect = UIScreen.main.bounds
var array = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dignissim enim sit amet venenatis urna cursus eget nunc. Congue nisi vitae suscipit tellus mauris a diam maecenas sed. Ac tortor vitae purus faucibus ornare suspendisse sed nisi lacus. Arcu risus quis varius quam quisque. Sit amet consectetur adipiscing elit pellentesque. Tellus cras adipiscing enim eu. Eros in cursus turpis massa tincidunt. Non diam phasellus vestibulum lorem sed risus ultricies tristique. Enim nunc faucibus a pellentesque sit amet. Aliquet nec ullamcorper sit amet. Turpis massa tincidunt dui ut. Iaculis urna id volutpat lacus laoreet non curabitur. Congue mauris rhoncus aenean vel elit scelerisque mauris pellentesque. Commodo ullamcorper a lacus vestibulum sed arcu non odio. Quis auctor elit sed vulputate. Molestie nunc non blandit massa enim nec. Tempus imperdiet nulla malesuada pellentesque elit eget gravida cum sociis. Facilisis volutpat est velit egestas dui id ornare arcu. Sociis natoque penatibus et magnis dis parturient montes nascetur ridiculus."]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
CV.delegate = self
CV.dataSource = self
}
}
extension ViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
array.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = CV.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
cell.TextPosted.text = array[indexPath.item]
//cell.layoutIfNeeded()
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: screenSize.width, height: 175)
}
}
现在你的标签:
import UIKit
class Cell: UICollectionViewCell {
@IBOutlet weak var TextPosted: UILabel!
override func awakeFromNib() {
let screenSize: CGRect = UIScreen.main.bounds
contentView.widthAnchor.constraint(equalToConstant: screenSize.width).isActive = true
contentView.heightAnchor.constraint(greaterThanOrEqualToConstant: 175).isActive = true
TextPosted.numberOfLines = 0
TextPosted.translatesAutoresizingMaskIntoConstraints = false
TextPosted.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
//Left Side
TextPosted.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true
//Right Side
TextPosted.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
//Bottom Space between contentView and text
TextPosted.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -10).isActive = true
}
}
我在 CollectionView 单元格中使用带有 CollectionView 的故事板。我需要里面的一个根据数组中给定的文本调整高度并将其连接到我的 UILabel。
我发布了一个答案,欢迎使用!
这里有一个 snippet 测量字符串的大小。 (您可能需要将默认值 220 更改为适合您需要的值。)
extension String {
func size(width:CGFloat = 220.0, font: UIFont = UIFont.systemFont(ofSize: 17.0, weight: .regular)) -> CGSize {
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = self
label.sizeToFit()
return CGSize(width: label.frame.width, height: label.frame.height)
}
}
在您的 collectionViewController 中,确保您在视图控制器中继承 UICollectionViewDelegateFlowLayout
:
class yourViewController : UICollectionViewController, UICollectionViewDelegateFlowLayout
然后实现sizeForItemAt函数:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let yourString = yourStringArray[indexPath.row]
let padding = CGSize.init(width: 20, height: 20)
let textSize = yourString.size(width: collectionView.frame.width) // you can also specify a font with fontSize and weight. Default is set to the system font with fontSize 17.
return CGSize.init(width: textSize.width + (padding.width / 2), height: textSize.height + (padding.height / 2))
}
注意:我已经在您的单元格 10 的所有边上添加了任意填充,因此您可能需要根据您希望单元格的外观添加填充。 'size' 仅根据文本测量标签的大小。
这正是我一直在寻找的...但任何人都可以随意将它与您的故事板 collectionView 一起使用。
您的 collectionView 所在位置:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var CV: UICollectionView!
let screenSize: CGRect = UIScreen.main.bounds
var array = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dignissim enim sit amet venenatis urna cursus eget nunc. Congue nisi vitae suscipit tellus mauris a diam maecenas sed. Ac tortor vitae purus faucibus ornare suspendisse sed nisi lacus. Arcu risus quis varius quam quisque. Sit amet consectetur adipiscing elit pellentesque. Tellus cras adipiscing enim eu. Eros in cursus turpis massa tincidunt. Non diam phasellus vestibulum lorem sed risus ultricies tristique. Enim nunc faucibus a pellentesque sit amet. Aliquet nec ullamcorper sit amet. Turpis massa tincidunt dui ut. Iaculis urna id volutpat lacus laoreet non curabitur. Congue mauris rhoncus aenean vel elit scelerisque mauris pellentesque. Commodo ullamcorper a lacus vestibulum sed arcu non odio. Quis auctor elit sed vulputate. Molestie nunc non blandit massa enim nec. Tempus imperdiet nulla malesuada pellentesque elit eget gravida cum sociis. Facilisis volutpat est velit egestas dui id ornare arcu. Sociis natoque penatibus et magnis dis parturient montes nascetur ridiculus."]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
CV.delegate = self
CV.dataSource = self
}
}
extension ViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
array.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = CV.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
cell.TextPosted.text = array[indexPath.item]
//cell.layoutIfNeeded()
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: screenSize.width, height: 175)
}
}
现在你的标签:
import UIKit
class Cell: UICollectionViewCell {
@IBOutlet weak var TextPosted: UILabel!
override func awakeFromNib() {
let screenSize: CGRect = UIScreen.main.bounds
contentView.widthAnchor.constraint(equalToConstant: screenSize.width).isActive = true
contentView.heightAnchor.constraint(greaterThanOrEqualToConstant: 175).isActive = true
TextPosted.numberOfLines = 0
TextPosted.translatesAutoresizingMaskIntoConstraints = false
TextPosted.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
//Left Side
TextPosted.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true
//Right Side
TextPosted.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
//Bottom Space between contentView and text
TextPosted.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -10).isActive = true
}
}