簡體   English   中英

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

}
}

這是我的截圖:

屏幕顯示在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)!")

}
}

輸出相同:

更新后的輸出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)!")        
}
}

storyviewcell里面的故事板一個標簽。 使用Autolayout。

標簽約束。

輸出

產量

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
    }

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM