【问题标题】:UITextview height in UITableview swiftUITableview swift中的UITextview高度
【发布时间】:2016-04-17 14:29:53
【问题描述】:

UITableViewCell 中设置UITextview 时遇到问题。由于函数 heightforrowatindexpathcellforrowatindexpath 之前运行,所以我无法计算 UITextview 的内容大小。

我只是通过cellforrowatindexpath 函数中的textview.contentSize.height 来计算大小。

我基本上希望UITextview contentHeight 适合UITableViewCell,因此每个UITextView 都看不到滚动,它会通过增加UITableViewCell 的高度来显示全部内容。

我也是一个UILabel,就在UITableViewCell中的UITextView之上,我试图为两者设置约束,但无法实现我的目标。

如何在以下函数中动态计算UITableViewCell 的大小:

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

}

P.S: 是否可以根据设备高度使用自动布局或其他技术稍微增加UITableViewCell 的高度。

【问题讨论】:

    标签: ios swift uitableview autolayout uitextview


    【解决方案1】:

    您可以只传递带有内容的 textView 以计算 textView 的高度

    func calculateHeight(textView:UITextView, data:String) -> CGRect {
    
        var newFrame:CGRect! 
    
        // I was using the HTML content here. If your content is not HTML you can just pass the stringValue to your textView
        do {
            let attr = try NSAttributedString(data: html.dataUsingEncoding(NSUTF16StringEncoding)!, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes: nil)
            textView.attributedText = attr
    
        }catch {
            //Handle Exceptions
        }
    
        let fixedWidth = textView.frame.size.width
        textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
        let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
        newFrame = textView.frame
        newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
        print("height \(newFrame.height)")
        return newFrame
    }
    

    您可以在您的heightForRowAtIndex 中调用此方法,这样您就可以获得一个新的更新帧,您可以从中获取新的更新高度。

    请确保将scrollEnabled 保留为cellForRowAtIndexPath 中单元格textView 的false

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
            //Cell making here......
    
            cell.yourTextView.scrollEnabled = false
            return cell  
        }
    }
    

    【讨论】:

      【解决方案2】:

      1) 在 heightForRowAtIndexPath 中,给单元格大小如下:

      返回 UITableViewAutomaticDimension

      2) ...并添加以下内容:

      覆盖 func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 返回 UITableViewAutomaticDimension }

      希望对你有帮助……

      【讨论】:

        猜你喜欢
        • 2017-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多