【问题标题】:UITextView in Cell SwiftCell Swift 中的 UITextView
【发布时间】:2017-09-15 02:13:46
【问题描述】:

几个小时以来,我一直在处理这些限制,无法弄清楚这一点。 我的文本视图需要动态单元格高度。

如您所见,它与我的时间戳重叠。截至目前,我对时间戳的限制为零(无)。我已经尝试了所有可能的组合来完成这项工作,但我无法做到。

也在用

   override func viewDidLoad() {
        super.viewDidLoad()



        //TableView Cell word wrap (Dynamic Text)
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.estimatedRowHeight = 78
        self.tableView.rowHeight = UITableViewAutomaticDimension

【问题讨论】:

  • 尝试为您的消息标签提供底部约束。(前导、尾随、顶部、底部)
  • 这是一个 textView 而不是标签。我试过了。
  • 使用时间戳标签设置底部约束并禁用 textview 的滚动。

标签: ios swift swift3 uitextview


【解决方案1】:

timeStamp 和消息之间的用户垂直间距,并将常量设置为 >=2

【讨论】:

  • 那么我应该对时间戳设置什么限制?
  • 我会将它设置为默认值,它会向您显示高度和底部间距。 @codechicksrock
  • 它似乎正在使用垂直约束,但现在我无法弄清楚它的时间戳约束。
  • 设置时间戳的宽度、高度、底部和左侧间距。将宽度设置为您知道时间戳不会超过的值。然后对齐时间戳文本左对齐。我会做底部间距 2 和左侧间距 6 @codechicksrock
  • 我似乎仍然无法正确处理。垂直起搏似乎有效,但不能动态调整单元格的大小,因为我无法正确获取时间戳
【解决方案2】:

如果您的单元格高度取决于文本大小,请遵循以下步骤:在您的 ViewController.swift 中添加方法

    func calculateHeight(inString:String) -> CGFloat {
         let messageString = inString
         let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)]

     let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)

     let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)

      let requredSize:CGRect = rect
      return requredSize.height
}

设置文本标签的宽度然后调用这个函数:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            heightOfRow = self.calculateHeight(inString: conversations[indexPath.row].description)

            return (heightOfRow + 60.0)
    }

对于基本单元:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
           return UITableViewAutomaticDimension
    }

此功能不适用于自定义单元格。

如果您的单元格高度取决于图像高度,则返回图像高度 + someFloatValueAccordingToYourChoice。

希望它会起作用。

【讨论】:

  • func calculateHeight(inString:String) 中的 width: 222.0 是什么?
  • func calculateHeight(inString:String) 太棒了:D
  • 我用它作为单元格宽度。很高兴它有帮助:)
  • :p 你是老板。我的错。
【解决方案3】:

对于 Swift 3.1、4.0

通过设置约束和UITableViewAutomaticDimensions来实现。

第 1 步:

第 2 步:

第 3 步:

第 4 步:

删除UITextView的滚动

第 5 步:

添加下面的代码,

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

    return UITableViewAutomaticDimension
}

注意:

如果您有UILabel,则将上述解决方案中的UITextView 替换为UILabellabel.numberOfLines = 0

输出:

【讨论】:

  • 你是一个了不起的帮助我不能更伟大。
  • 很棒的解决方案!我需要它。
  • @mumu,谢谢队友:D
猜你喜欢
  • 2022-01-24
  • 2021-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 2018-07-03
相关资源
最近更新 更多