Hemant Bavle
Hemant Bavle

Reputation: 3327

Text getting overlapped in uitableview cells in iOS swift

I have created a prototype UITableViewCell on storyboard.It contains 1 ImageView, 3 labels to display the content. All the controls have outlets in corresponding subclass of UITableViewCell. I display messages which can be multi line. So I had to add following methods

 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

 func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

The text of the labels is getting overlapped and it happens whenever I scroll the tableview. It is only happening with either first 2 rows or the last row.But as i searched on google, I found that it can happen on any row any time. Here's my code of the extension which is commonly written.

extension ConversationViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let count = selectedConversation?.msgArrayWithBodyText.count {
            return count
        }
        return 0
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier(conversationMessageIdentifier, forIndexPath: indexPath) as! ConversationMessageTableViewCell
        let currMsg =  selectedConversation.msgArrayWithBodyText[indexPath.row]
        cell.userFullNameLabel.text = currMsg.senderName
        cell.dateLabel.text = selectedConversation.getShortDateForMessage(currMsg.timeSent)
        cell.messageBodyLabel.text = currMsg.bodyText //Constants.testString

        let imageUrl = "\(Constants.serverUrl)/api/users/\(currMsg.senderId)/profilePicture"
        if let item = ImageCache.sharedInstance.objectForKey(imageUrl) as? CacheableItem {
            print("\(imageUrl) found in cache, expiresAt: \(item.expiresAt)")
            cell.userImageView.image = UIImage(data: item)
        } else {
            cell.userImageView.image = UIImage(named: "Profile")

            self.imageDownLoadingQueue.addOperationWithBlock({
                if let url = NSURL(string: imageUrl) {
                    if let purgableData = NSPurgeableData(contentsOfURL: url) {
                        if let downloadedImage = UIImage(data: purgableData) {
                            print("cache: \(imageUrl)")

                            let item = CacheableItem()
                            item.setData(purgableData)
                            ImageCache.sharedInstance.setObject(item, forKey: imageUrl)

                            NSOperationQueue.mainQueue().addOperationWithBlock({
                                if let updateCell = tableView.cellForRowAtIndexPath(indexPath) as? ConversationMessageTableViewCell {
                                    updateCell.userImageView.image = downloadedImage
                                }
                            })
                        }
                    }
                }
            })
        }
        //cell.clipsToBounds = true
        return cell
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if cell.respondsToSelector(Selector("setSeparatorInset:")) {
            cell.separatorInset = UIEdgeInsetsZero
        }
        if cell.respondsToSelector(Selector("setLayoutMargins:")) {
            cell.layoutMargins = UIEdgeInsetsZero
        }
        if cell.respondsToSelector(Selector("setPreservesSuperviewLayoutMargins:")) {
            cell.preservesSuperviewLayoutMargins = false
        }

        cell.backgroundColor = UIColor.clearColor()
        cell.backgroundView = UIView(frame:cell.frame)
        if(cell.backgroundView?.layer.sublayers?.count > 1){
            cell.backgroundView?.layer.sublayers?.removeAtIndex(0)
        }
        let layer = self.getGradientLayer(indexPath.row)
        cell.backgroundView?.layer.insertSublayer(layer, atIndex: 0)

    }
}

And here's the subclass of UITableViewCell i have written for the protyped cell.

class ConversationMessageTableViewCell: UITableViewCell {
    @IBOutlet weak var userImageView: UIImageView!
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var userFullNameLabel: UILabel!
    @IBOutlet weak var messageBodyLabel: UILabel!

    @IBOutlet weak var messageBodyLabelHeightConstraint: NSLayoutConstraint!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

        userImageView.layer.borderColor = UIColor.clearColor().CGColor
        userImageView.layer.borderWidth = 1.0
        userImageView.layer.cornerRadius = (userImageView.frame.height/2)
        userImageView.clipsToBounds = true
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

Here's the edited screen shot (I have blackened out the name and faces)

This is what happens

Help required!

I can see long text not getting messed up,but it only happens with small texts.

Basically, this only happens when i scroll the tableview up and down few times. All the text is displayed properly when tableview loads, but then messes up and then clears out for a while and again messes up.

Upvotes: 0

Views: 888

Answers (1)

Hemant Bavle
Hemant Bavle

Reputation: 3327

I found the solution to this problem. There is an option in story board which says Clear Graphics Context which basically clears the graphics for the label before redrawing it.

Upvotes: 1

Related Questions