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

UICollectionViewCell labels overlap each other in background color

我是 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)!")

}
}

这是我的屏幕截图:

最后我想要输出,就像每个单元格单独出现一样,没有重叠,也没有标签修剪。如果 "How Are you?" 的标签宽度为 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)!")

}
}

输出相同:

在swift2.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])")
}

在Swift3.0

不要忘记查看 class 声明。它也扩展了 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 内的故事板一个标签。使用自动布局。

输出 :

func widthForView1(_ text:String, font:UIFont, height:CGFloat) -> CGFloat{let 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)
}

根据字符串的长度调整 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
    }