UICollectionViewCell 标签在背景颜色中相互重叠

Posted

技术标签:

【中文标题】UICollectionViewCell 标签在背景颜色中相互重叠【英文标题】:UICollectionViewCell labels overlap each other in background color 【发布时间】:2017-01-17 10:07:17 【问题描述】:

我是 ios 新手,但可以使用 Swift 3 编写代码。我根本不懂 Objective-C。

我正在学习UICollectionView,并且我有一组字符串数组。当我将自定义宽度设置为单元格时,它效果不佳。标签相互重叠。之后,当我使用 flowLayout 时,它会修剪标签。一行中5个单元格的确定数量也是固定的。

这是我的代码:

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource 

let reuseIdentifier = "cell"
var items = ["12", "2", "3221", "434", "52342","5646445646454464654646464", "bdvjsd", "adscfaaaw", "How are you?"];

@IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
override func viewDidLoad() 
    super.viewDidLoad()



override func didReceiveMemoryWarning() 
    super.didReceiveMemoryWarning()


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    return self.items.count


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

    cell.myLabel.text = self.items[indexPath.item]
    cell.backgroundColor = UIColor.yellow
    let a = (items[indexPath.item]).size(attributes: nil)
    cell.frame.size.width = a.width + 20

    return cell


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) 
    // handle tap events
    flowLayout.minimumInteritemSpacing = 5.0
    print("You selected cell #\((items[indexPath.item]).size(attributes: nil).width)!")



这是我的截图:

最后我希望输出像每个单元格单独出现,没有重叠,也没有标签修剪。如果“你好吗?”标签的宽度是 x 那么包含该标签的单元格的宽度必须为 x+20(它只是假设)并且该标签或单元格不应与任何其他单元格或标签重叠

更新 1

这里是代码如果我改变了。

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource 

let reuseIdentifier = "cell"
var items = ["12", "2", "3221", "434", "52342","5646445646454464654646464", "bdvjsd", "adscfaaaw", "How are you?"];
var x:[Double] = []
var tempItems:[String] = []
var flag = true

@IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
override func viewDidLoad() 
    super.viewDidLoad()



override func didReceiveMemoryWarning() 
    super.didReceiveMemoryWarning()


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    return self.items.count


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath)
    let label: UILabel = (cell.viewWithTag(15) as! UILabel)
    label.text = self.items[indexPath.item]

    return cell


// collectionview layoutflow method. first this method call then other delagates method call.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize 

    let Labell : UILabel = UILabel()
    Labell.text =   self.items[indexPath.item]
    let labelTextWidth =   Labell.intrinsicContentSize.width
    return CGSize(width: labelTextWidth + 12, height: 35)


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) 
    // handle tap events

    print("You selected cell #\(indexPath.item)!")



而且输出是一样的:

【问题讨论】:

flowLayout.minimumInteritemSpacing = 5.0 评论这一行并检查它 @HimanshuMoradiya 修剪不是问题。但重叠是。我做了修剪以展示我尝试了很多方法但不起作用的例子 我对你的问题有点困惑,只需用你想要的实际输出来更新你的问题。 @HimanshuMoradiya 我已经更新了我的问题 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize if collectionView == coll_degree let labelTextWidth = self.dict_treatment_profile.valueForKey("degree_acheive")?. valueForKey("degree_name")?.objectAtIndex(indexPath.row) as? String.intrinsicContentSize().width return CGSize(width: labelTextWidth + 20, height: 45) 【参考方案1】:

在 swift 2.0 中

class MYVIEWCONTROLLER: UIViewController ,UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout

  var items = ["12", "2", "3221", "434", "52342","bdvjsd","Hello","5646445646454464654646464", "bdvjsd", "adscfaaaw", "How are you?"];

// collectionview delegates methods.
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
        return self.items.count


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("invitecell", forIndexPath: indexPath)
    let label: UILabel = (cell.viewWithTag(15) as! UILabel)
    label.text = self.items[indexPath.item]

    return cell


// collectionview layoutflow method. first this method call then other delagates method call.
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize 

    return CGSize(width: self.findHeightForText(self.items[indexPath.item], havingWidth: self.view.frame.size.width - 116, andFont: UIFont.systemFontOfSize(14.0)).width + 12, height: 35)


 func findHeightForText(text: String, havingWidth widthValue: CGFloat, andFont font: UIFont) -> CGSize 
        var size = CGSizeZero
        if text.isEmpty == false 
            let frame = text.boundingRectWithSize(CGSizeMake(widthValue, CGFloat.max), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
            size = CGSizeMake(frame.size.width, ceil(frame.size.height))
        
        return size

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)

    print("Selected item :\(self.items[indexPath.item])")

在 Swift 3.0 中

不要忘记查看类声明。它还扩展了 UICollectionViewDelegateFlowLayout

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout 

let reuseIdentifier = "cell"
var items = ["12", "2", "3221", "434", "52342","5646445646454446464", "bdvjsd", "adscfaaaw", "How are you?"];

@IBOutlet weak var myCollectionView: UICollectionView!
@IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
override func viewDidLoad() 
    super.viewDidLoad()


override func didReceiveMemoryWarning() 
    super.didReceiveMemoryWarning()


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
    let Labell : UILabel = UILabel()

    Labell.text =   self.items[indexPath.item]
    let labelTextWidth =   Labell.intrinsicContentSize.width
    return CGSize(width: labelTextWidth + 12, height: 35)



func findHeightForText(text: String, havingWidth widthValue: CGFloat, andFont font: UIFont) -> CGSize 
    var size = CGSize()
    if text.isEmpty == false 
        let frame = text.boundingRect(with: CGSize(width: widthValue, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        size = CGSize(width: frame.size.width, height: ceil(frame.size.height))
    
    return size

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    return self.items.count


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! MyCollectionViewCell
    cell.myLabel.text = self.items[indexPath.item]
    cell.myLabel.backgroundColor = UIColor.yellow

    return cell


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) 
    // handle tap events

    print("You selected cell #\(indexPath.item)!")        


collectionviewcell 内的故事板一个标签。使用自动布局。

输出

【讨论】:

【参考方案2】:
func widthForView1(_ text:String, font:UIFont, height:CGFloat) -> CGFloatlet label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: height))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.text = text
label.font = font
label.sizeToFit()
return label.frame.width

在 heightForRow 方法中

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize 
   let str = items[indexpath.row];
    let width = widthForView1(str,font:yourFont,yourHeight)
   return CGSizeMake(width, yourHeight)

【讨论】:

【参考方案3】:

根据字符串长度调整collectionView每一项的大小:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    
        let size = items[indexPath.item].size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 18.0)])
        return size
    

【讨论】:

以上是关于UICollectionViewCell 标签在背景颜色中相互重叠的主要内容,如果未能解决你的问题,请参考以下文章

根据标签文本自定义 UICollectionViewCell 自身大小

将渐变应用于 UICollectionViewCell 中的标签

UICollectionViewCell 标签在背景颜色中相互重叠

使用 UICollectionViewCell 内的 Textfield 更新标签

iOS:长按时在 uicollectionViewcell 上显示带有文本的标签

UICollectionViewCell 中图像的异步加载导致标签消失