简体   繁体   English

文本在iOS的uitableview单元格中重叠

[英]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. 我在情节UITableViewCell板上创建了一个原型UITableViewCell ,其中包含1个ImageView,3个用于显示内容的标签。 All the controls have outlets in corresponding subclass of UITableViewCell . 所有控件在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. 标签的文本越来越重叠,每当我滚动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. 它仅发生在前两行或最后一行。但是当我在google上搜索时,我发现它可以随时发生在任何行上。 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. 这是我为原型单元格编写的UITableViewCell的子类。

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) 这是编辑过的屏幕截图(我已经涂黑了名字和面孔)

这是怎么回事

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. 基本上,这仅在我上下滚动tableview几次时才会发生。 All the text is displayed properly when tableview loads, but then messes up and then clears out for a while and again messes up. 加载tableview时,所有文本均会正确显示,但随后会混乱,然后清除一段时间,然后再次混乱。

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. 故事板上有一个选项,内容为“清除图形上下文”,它基本上可以在重画标签之前清除标签的图形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM