ios - 获取自定义单元格中标签的高度以用于主视图 Controller 中的 heightForRowAt

标签 ios swift3

我有一个 View Controller ,它使用名为 searchCell 的自定义单元格来引入内容,我想知道如何获取标签 lblLeft 的高度并在 tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) 中使用它-> CGFloat 函数返回标签的高度。我在主视图 Controller 中使用的代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
    IndexPath) -> UITableViewCell {
    if searchMode == searching {
        let cell: MHSearchCell = tableView.dequeueReusableCell(withIdentifier: 
        MHSearchCell.ReusableIdentifier()) as! MHSearchCell

        cell.helper = helpers[indexPath.row]
        cell.delegate = self

        return cell
  }
}

在我的 MHSearchCell 中创建标签的部分代码,标签在此处连接为 IBOutlet:

lblLeft.text = ""

        if let expertiseCount = helper.expertise {

            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 5
            paragraphStyle.lineBreakMode = .byWordWrapping
            paragraphStyle.alignment = NSTextAlignment.center
            lblLeft.numberOfLines = 0

            let finalString = expertiseCount.map({$0.name!}).joined(separator: "   \u{00B7}   ")
            let finalAttributedString = NSMutableAttributedString(string: finalString, attributes: [NSParagraphStyleAttributeName:paragraphStyle])
            lblLeft.attributedText = finalAttributedString
        }

最佳答案

第一种方法是使用自动尺寸

1) 在标签上应用适当的约束,请检查下图。

enter image description here

确保 Storyboard中的标签行设置为 0

现在在 Controller 类中执行此操作:

//MArk-: ViewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        yourTableView.estimatedRowHeight = 142.0 // Default cell height from storyboard

        yourTableView.rowHeight = UITableViewAutomaticDimension
    }

表函数-:

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

另一种计算 estimatedHeightForLabel 的方法-:

1) 如上所述对标签应用相同的约束

2) 使用 NSString 的 boundingRect 方法从标签中找到单元格的准确高度 -:

TableView 函数-:

extension ViewController : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return value.count
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? testingCell
        cell?.textlabel.text = value[indexPath.row]
        return cell!
    }

    // Number of sections in table

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }// Default is 1 if not implemented

    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        let text = value[indexPath.row]
        let estimatedheight = calculateEstimatedHeight(text: text)
        return estimatedheight.height
    }

    func calculateEstimatedHeight(text:String) -> CGRect{
        let size = CGSize(width: view.frame.width, height: 1000)
        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        let attribute = [NSFontAttributeName:UIFont.systemFont(ofSize: 17)]
        let estimatedHeight = NSString(string: text).boundingRect(with: size, options: options, attributes: attribute, context: nil)
        return estimatedHeight
    }

记住-:

1) 提供与标签相同的字体大小。

2) 对于多行标签,使用选项作为 .usesLineFragmentOrigin

自定义单元类-:

import UIKit

class testingCell: UITableViewCell {

    @IBOutlet weak var textlabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

关于ios - 获取自定义单元格中标签的高度以用于主视图 Controller 中的 heightForRowAt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45680791/

相关文章:

xcode - 如何在 Swift 中生成 NSManagedObject 类而不是 Xcode 8 中的 Objective C?

ios - 在倒计时结束时重置或更改按钮标题

ios - AVSpeechSynthesizer 在后台运行后停止工作

iphone - iOS 中离线网站的最佳实践

ios - TableView 和外部数据源

android - iOS 中类似 Android 的水平线性进度条

ios - NSObject cancelPreviousPerformRequestsWithTarget 任何对象

ios - 如何仅从 CLLocation 中获取纬度和经度值,而不是快速获取完整的位置详细信息

swift - 如何在选择一行后隐藏tableView

ios - 将 JSON 数据加载到 TableView 不起作用