ios - UILabel 上的 SizeToFit 和自动布局

标签 ios swift autolayout uilabel

我有一个带有自动布局的动态单元格,其中包含图像和动态标签。目前我尝试绘制气泡图像,但我需要知道给定文本的标签的大小是多少。我不得不说,我总是收到一个错误的尺寸,当我滚动桌面 View 时,气泡图像被正确放置,但它会广告另一个气泡。

这是我的代码:

func imageCellAtIndexPath(indexPath:NSIndexPath) -> SenderTableViewCell{
    let cell = self.tableView.dequeueReusableCellWithIdentifier("SenderIdentifier") as! SenderTableViewCell
    cell.senderMessageLAbel.text = "fadfasdfasdfasdfasdfasdadfasdfsb"
    cell.senderMessageLAbel.sizeToFit()
    cell.senderNameLabel.text = "Stefan"

    let padding: CGFloat = 10.0

    // 4. Calculation of new width and height of the chat bubble view
    var viewHeight: CGFloat = 0.0
    var viewWidth: CGFloat = 0.0

        viewHeight = cell.senderMessageLAbel.frame.size.height + padding
        viewWidth = cell.senderMessageLAbel.frame.size.width  + padding/2

    if viewHeight > viewWidth {
        viewHeight = cell.senderMessageLAbel.frame.size.width  + padding/2
        viewWidth = cell.senderMessageLAbel.frame.size.height + padding
    }

    let bubbleImageFileName = "bubbleMine"
    let imageViewBG : UIImageView = UIImageView(frame: CGRectMake(cell.senderMessageLAbel.frame.origin.x - 5, cell.senderMessageLAbel.frame.origin.y - 10,viewWidth,viewHeight ))
    imageViewBG.image = UIImage(named: bubbleImageFileName)?.resizableImageWithCapInsets(UIEdgeInsetsMake(14, 22,17 , 20))
    cell.insertSubview(imageViewBG, atIndex: 0)
    imageViewBG.center = cell.senderMessageLAbel.center

    return cell
}

我无法弄清楚我的代码出了什么问题。有什么建议么?

最佳答案

我假设您的函数正在 cellForItemAtIndexPath 被调用UICollectionView数据源的功能。每当需要绘制进入 View 的 Collection View 单元格时,该函数就会被多次调用。因此,每次发生这种情况时,您都会插入 imageViewBG到单元格,从而复制。

一个快速的解决方案是将特定标签添加到 imageViewBG如下所示,每次重新添加之前将其删除。

cell.viewWithTag(99)?.removeFromSuperview()
let imageViewBG = //Configure
imageViewBG.tag = 99
cell.insertSubview(imageViewBG, atIndex: 0)

虽然这将有助于解决重复问题,但我强烈建议您将 imageView 添加到 Storyboard 上的自定义单元格,并配置它应在 cellForItemAtIndexPath 中显示的图像。 .

关于ios - UILabel 上的 SizeToFit 和自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33648592/

相关文章:

iphone - Website Push ID 的用途是什么?它与普通的 APNS 有何不同?

ios4.3.4 : MFMailComposer doesn't send an email, 但返回 MFMailComposeResultSent 状态

ios - 苹果开发者账户中的公平竞争流媒体证书错误

ios - Swift - 如何从 json 获取数据类型

ios - 使用 iOS Auto Layout 在 subview Controller 和它的父 View 之间建立约束

ios - 检测 CCSprite(包含在数组中)在屏幕上拖动手指的触摸

swift - 如何通过 UISearchBar 文本过滤掉内容?

ios - UIView 无法在具有自动布局的 UIScrollView 中正确居中

swift - UIView 子类在初始化时固定高度

ios - swift : a function returning a variable or just a getter variable 什么更好