2017-01-17 5 views
1

Я новичок в iOS, но могу кодировать в Swift 3. Я вообще не знаю Objective-C.Ярлыки UICollectionViewCell перекрывают друг друга в цвете фона

Я изучаю 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

Наконец, я хочу вывода, как в каждой клетке не появляется в индивидуальном порядке не перекрываются и не подгонка этикетки. Если ширина метки для «Как вы?» есть х, то ячейка, содержащая эту метку должна быть шириной х + 20 (его просто предположение), и что метки или ячейки не должны перекрываться на любой другой клетке или этикетке

UPDATE 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

+0

flowLayout.minimumInteritemSpacing = 5,0 комментарий этой линии и проверить его –

+0

@HimanshuMoradiya подрезка не проблема. Но перекрывается.Я сделал обрезку, чтобы показать пример, что я пробовал много способов, но не работает –

+0

Я немного путаюсь в вашей проблеме, просто обновляю ваш вопрос тем, что вы хотите получить. –

ответ

0

В быстры 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. Используйте Autolayout.

label constrain.

Выход:

Output

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} 

в методе 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) 
} 
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