UICollectionViewCell标签以背景颜色

时间:2017-01-17 10:07:18

标签: 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

3 个答案:

答案 0 :(得分:0)

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

故事板中集合视图内的一个标签。使用Autolayout。

label constrain.

输出

Output

答案 1 :(得分:0)

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}

in 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)
}

答案 2 :(得分:0)

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

enter image description here