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

标签 ios swift uicollectionview swift3 uicollectionviewcell

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

}
}

这是我的截图:

Screen appear on Load

最后,我希望输出像每个单元格单独显示一样,没有重叠,也没有标签修剪。如果“你好吗?”标签的宽度是 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)!")

}
}

输出是一样的:

Output After Update 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)!")        
}
}

Collection View 单元内的 Storyboard一个标签。使用自动布局。

label constrain.

输出:

Output

关于ios - UICollectionViewCell 标签在背景色中相互重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41694217/

相关文章:

ios - 预填充 UICollectionView 单元重用队列

ios - 如何更改 Apple 应用商店中已发布 iOS 应用的地区可用性

ios - 如何确定应用程序因电话调用或用户按下主页按钮而进入后台状态

ios - Xcode 上的 Swift._ArrayBuffer._copyContents

ios - 如何在具有 dequeueReusableCell 的同时以编程方式设置 tableview 样式以具有副标题?

ios - Swift-在另一个ViewController中的ContainerView中访问UIButton

iOS;不支持的像素格式

iphone - 更快的iPhone PNG动画

ios - 为什么 UICollectionView reloadData 会导致我的应用崩溃?

ios - 如何从另一个类执行一个类的 collectionView 方法?