2016-01-19 3 views
1

Я пишу чат-приложение для Apple-tv, и у меня возникла проблема с отображением пользовательского вида в чате ячеек.UICollectionview view in cell неправильный рисунок

У меня есть код:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> 
     UICollectionViewCell { 
      var myCell = self.chatCollectionView.dequeueReusableCellWithReuseIdentifier(chatCellIdentifier, forIndexPath: indexPath) as UICollectionViewCell 
      myCell.removeFromSuperview() 
       currentIndexPath = indexPath 
       if flag[indexPath.row]==0 
       { 
       myCell = sendBotMessage(historyString[indexPath.row], path: indexPath, collectionView: chatCollectionView) 
       } 
       else 
       { 
       myCell = sendUserMessage(historyString[indexPath.row], path: indexPath, collectionView: chatCollectionView) 
       } 
      return myCell 
    } 

код отображает две версии сообщений, как можно видеть, sendBotMessage и sendUserMessage. Проблема в том, что отображение следующей ячейки отображается некорректно ранее. Первый запуск с 1-sendBotMessage зрения first run и после добавления второго пункта second run второй (справа) сообщений с помощью добавления sendUserMessage, другого вида. вся история «соответствия» хранится в historyString - массив строки типа. Хранение организовано правильно, так как при исчезновении ошибок отображения прокрутки. По этой причине можно сделать вывод о правильности функций рендеринга.
Все новое сообщение добавляется в historyString, после чего необходимо перерисовать вызов reloadData() и collectionView.

Где я могу ошибаться? Я попытался очистить subview за collectionView, отключить прокрутку анимации, это не помогло.

код процедуры рисования вида по: FUNC sendUserMessage (текст: String, путь: NSIndexPath, CollectionView: UICollectionView) -> UICollectionViewCell {

let userMessage = text 
    let textSize = getTextFrameSize(userMessage) 
    let frameForMessage = getFrameforView(textSize) 

    let messageBuble = Chat_ViewInCell(frame: frameForMessage, textSize: textSize, text: userMessage) 
    messageBuble.backgroundColor = UIColor.clearColor() 

    let avatarImage = UIImage(named: "\(userAvatar+1).png") 
    let avatarView = UIImageView(image: avatarImage) 
    avatarView.contentMode = UIViewContentMode.ScaleAspectFit 

    let totalX = messageBuble.frame.width + 340 
    let constraint = 1750 - totalX 
    messageBuble.frame.origin = CGPointMake(constraint, 0) 
    avatarView.frame = CGRectMake(messageBuble.frame.maxX + 10, 0, 170, 170) 

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(chatCellIdentifier, forIndexPath: path) as! chatCollectionViewCell 
    //добавляем, счастье, радуемся 
    cell.addSubview(messageBuble) 
    cell.addSubview(avatarView) 
    return cell 
} 

функ sendBotMessage (текст: String, путь: NSIndexPath, CollectionView: UICollectionView) -> UICollectionViewCell {

let userMessage = text 
    let textSize = getTextFrameSize(userMessage) 
    let frameForMessage = getFrameforView(textSize) 

    let messageBuble = bot_ViewInCell(frame: frameForMessage, textSize: textSize, text: userMessage) 
    messageBuble.backgroundColor = UIColor.clearColor() 

    let avatarImage = UIImage(named: partner_image) 
    let avatarView = UIImageView(image: avatarImage) 
    avatarView.contentMode = UIViewContentMode.ScaleAspectFit 
    avatarView.frame = CGRectMake(0, 0, 170, 170) 
    let constraint = avatarView.frame.maxX + 10 
    messageBuble.frame.origin = CGPointMake(constraint, 0) 

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(chatCellIdentifier, forIndexPath: path) as! chatCollectionViewCell 
    //добавляем в возвращаемую ячейку 
    cell.addSubview(avatarView) 
    cell.addSubview(messageBuble) 
    return cell 
} 

После рекомендуемых изменений с таможенной CollectionCellView у меня есть этот код:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> 
    UICollectionViewCell { 
     var myCell = chatCollectionView.dequeueReusableCellWithReuseIdentifier(chatCellIdentifier, forIndexPath: indexPath) as! chatCollectionViewCell 
     var customCell = myCell 
      if flag[indexPath.row]==0 
      { 
      customCell = sendBotMessage(historyString[indexPath.row], path: indexPath, collectionView: collectionView) 
      } 
      else 
      { 
      customCell = sendUserMessage(historyString[indexPath.row], path: indexPath, collectionView: collectionView) 
      } 
     myCell = customCell 
     currentIndexPath = indexPath 
     return myCell 
} 

Функция на рисунке тоже есть изменения в пользовательские ячейки:

func sendUserMessage(text : String, path : NSIndexPath, collectionView : UICollectionView) -> chatCollectionViewCell { 

    let userMessage = text 
    let textSize = getTextFrameSize(userMessage) //высчитали необходимые размеры лейбла 
    let frameForMessage = getFrameforView(textSize) //высчиитали необходимые размеры всей вьюшки 

    let messageBuble = Chat_ViewInCell(frame: frameForMessage, textSize: textSize, text: userMessage) 
    messageBuble.backgroundColor = UIColor.clearColor() 

    //создаем аватар 
    let avatarImage = UIImage(named: "\(userAvatar+1).png") 
    let avatarView = UIImageView(image: avatarImage) 
    avatarView.contentMode = UIViewContentMode.ScaleAspectFit 

    //считаем отступ до правого края, позицию аватара 
    let totalX = messageBuble.frame.width + 340 
    let constraint = 1750 - totalX 
    messageBuble.frame.origin = CGPointMake(constraint, 0) 
    avatarView.frame = CGRectMake(messageBuble.frame.maxX + 10, 0, 170, 170) 

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(chatCellIdentifier, forIndexPath: path) as! chatCollectionViewCell 
    //добавляем, счастье, радуемся 
    cell.addSubview(messageBuble) 
    cell.addSubview(avatarView) 
    return cell 
} 

    func sendBotMessage(text : String, path : NSIndexPath, collectionView : UICollectionView) -> chatCollectionViewCell { 

    let userMessage = text 
    let textSize = getTextFrameSize(userMessage) //высчитали необходимые размеры лейбла 
    let frameForMessage = getFrameforView(textSize) //высчиитали необходимые размеры всей вьюшки 

    //создали всю вьюшку 
    let messageBuble = bot_ViewInCell(frame: frameForMessage, textSize: textSize, text: userMessage) 
    messageBuble.backgroundColor = UIColor.clearColor() 

    //создаем аватар и считаем его позицию 
    let avatarImage = UIImage(named: partner_image) 
    let avatarView = UIImageView(image: avatarImage) 
    avatarView.contentMode = UIViewContentMode.ScaleAspectFit 
    avatarView.frame = CGRectMake(0, 0, 170, 170) 
    let constraint = avatarView.frame.maxX + 10 
    messageBuble.frame.origin = CGPointMake(constraint, 0) 

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(chatCellIdentifier, forIndexPath: path) as! chatCollectionViewCell 
    //добавляем в возвращаемую ячейку 
    cell.addSubview(avatarView) 
    cell.addSubview(messageBuble) 
    return cell 
} 

Но проблемы времени не исправляет ... Что я делаю неправильно с пользовательским CollectionViewCell? Я должен сделать что-то другое?

+1

Не удаляйте FromSuperView и покажите код 'sendBotMessage()' и 'sendUserMessage()'. Мое предположение: у вас проблема с повторным использованием ячеек. В 'sendBotMessage()' и '' sendUserMessage() 'вам может понадобиться очистить ячейку. – Larme

+0

добавлено sendBotMessage и sendUserMessage –

+2

Используйте пользовательский UICollectionViewCell, не добавляйте subview каждый раз в свою коллекциюViewCell. Ячейки повторно используются. – Larme

ответ

0

Проблема исправлена! Я не знаю о методе prepareForReuse(). Так просто, в пользовательском классе defeniton я должен переопределить его метод и вызвать для subviews cleararsContextBeforeDrawing и removeFromSuperview. Код:

class chatCollectionViewCell: UICollectionViewCell { 

@IBOutlet weak var view: Chat_ViewInCell! 

override func prepareForReuse() { 
    super.prepareForReuse() 
    for currView in self.subviews 
    { 
     currView.clearsContextBeforeDrawing = true 
     currView.removeFromSuperview() 
    } 
} 

Все работало, без неправильной перерисовки.

Смежные вопросы