代码之家  ›  专栏  ›  技术社区  ›  developer

UITableview swift中的UITextview高度

  •  0
  • developer  · 技术社区  · 10 年前

    我在设置时遇到了一个问题 UITextview 在里面 UITableViewCell .作为功能 延伸高度 之前正在运行 用于扩展的单元格 所以我无法计算 UI文本视图 .

    我通过简单地计算尺寸 textview.contentSize.height 在里面 cellforrowatindexpath 作用

    我基本上想要 UI文本视图 contentHeight适合 UI表格视图单元格 因此,每个 UITextView 它将通过增加 UI表格视图单元格 .

    我也是 UILabel 就在 UI文本视图 在里面 UI表格视图单元格 我试着为这两种情况设定限制,但无法实现我的目标。

    如何计算 UI表格视图单元格 动态地执行以下功能:

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

    P.S:是否可以使用增加 UI表格视图单元格 使用自动布局或其他技术,根据设备高度稍微调整高度。

    2 回复  |  直到 10 年前
        1
  •  3
  •   Rajan Maheshwari    10 年前

    您只需将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 false 在中查看 cellForRowAtIndexPath

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
            //Cell making here......
    
            cell.yourTextView.scrollEnabled = false
            return cell  
        }
    }
    
        2
  •  1
  •   Marcos    9 年前

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

    return UITableViewAutomaticDimension

    2) …并添加以下内容:

    覆盖函数tableView(tableView:UITableView,estimatedHeightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat公司{ return UITableViewAutomaticDimension }

    我希望这有帮助。。。

    推荐文章