草庐IT

ios - 自动调整 Tableview 单元格到单元格内容(SWIFT)

coder 2023-09-16 原文

我正在尝试让我的 tableview 正常工作,因此当单击一个单元格时,它会自动调整大小以适合单元格内的内容。 (不同数量的文字会自动调整大小不同。

Cell when not clicked (first state and size it should go back to when clicked = 44.0

因此对于此图像,这是每个单元格将仅处于默认和取消选择状态的阶段。白色文本将是唯一可见的内容。

Cell clicked state. resizes to my "let selectedCellHeight: CGFloat = 88.0 " constant. Which needs to automatically size to fit the green text no matter how much is in there.

这是我的 tableview 和 viewcontroller 的完整代码。

import UIKit

class TasksViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tblTasks: UITableView!

//For persisting data
let defaults = UserDefaults.standard


override func viewDidLoad() {
    super.viewDidLoad()



    self.tblTasks.backgroundColor = UIColor(red: 64/255.0, green: 67/255.0, blue: 68/255.0, alpha: 0)


    self.tblTasks.reloadData()
    self.tblTasks.register(UINib(nibName: "WhiteTaskTableViewCell", bundle: nil), forCellReuseIdentifier: "nameCell")
    tblTasks.tableFooterView = UIView()

    let darkModeColor = UIColor(red: 52/255.0, green: 55/255.0, blue: 55/255.0, alpha: 1.0)
    view.backgroundColor = darkModeColor


    tblTasks.dataSource = self;

    // Do any additional setup after loading the view.
}



override func viewWillAppear(_ animated: Bool) {
    self.tblTasks.reloadData()
}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return taskMgr.tasks.count

}



//Define how our cells look - 2 lines a heading and a subtitle
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{


    let identifier = "nameCell"
    var cell: WhiteTaskTableViewCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? WhiteTaskTableViewCell

    if cell == nil {
        tableView.register(UINib(nibName: "WhiteTaskTableViewCell", bundle: nil), forCellReuseIdentifier: identifier)
        cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? WhiteTaskTableViewCell
    }


    //        Assign the contents of our var "items" to the textLabel of each cell
    //        cell.textLabel!.text = taskMgr.tasks[indexPath.row].name
    //        cell.detailTextLabel!.text = taskMgr.tasks[indexPath.row].desc

    cell.TaskNameLabel.text = taskMgr.tasks[indexPath.row].name
    cell.NotesLabel.text = taskMgr.tasks[indexPath.row].note

    cell.selectionStyle = .none



    return cell

}



func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
}



   func tableView(_ willDisplayforRowAttableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cell.backgroundColor = UIColor(red: 64/255.0, green: 67/255.0, blue: 68/255.0, alpha: 0)
}



func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // handle delete (by removing the data from your array and updating the tableview)

        taskMgr.removeTask(indexPath.row)
        tblTasks.reloadData()
    }
}



   // EXPAND CELL ON CLICK


// Global Variables/Constants

var selectedCellIndexPath: NSIndexPath?

let selectedCellHeight: CGFloat = 88.0
let unselectedCellHeight: CGFloat = 44.0

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

    self.tblTasks.rowHeight = UITableViewAutomaticDimension

    if selectedCellIndexPath == indexPath as NSIndexPath?  {
        return selectedCellHeight
    }
    return unselectedCellHeight
}



 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if selectedCellIndexPath != nil && selectedCellIndexPath == indexPath as NSIndexPath? {
        selectedCellIndexPath = nil
    } else {
        selectedCellIndexPath = indexPath as NSIndexPath?
    }

    tableView.beginUpdates()
    tableView.endUpdates()

    if selectedCellIndexPath != nil {
        // This ensures, that the cell is fully visible once expanded
        tableView.scrollToRow(at: indexPath as IndexPath, at: .none, animated: true)
    }
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/


}

我乐于接受任何帮助和见解。非常感谢。

最佳答案

您需要为您的 UITableView 设置一个 Outlet,并将 rowHeight 参数设置为 UITableViewAutomaticDimension。您还需要将 estimatedRowHeight 设置为适合您需要的值。这样 Cell 的大小将适合其内容的大小。

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
      super.viewDidLoad()        
      tableView.estimatedRowHeight = 55
      tableView.rowHeight = UITableViewAutomaticDimension
}

为此,您需要为单元格的每个元素设置自动布局约束。

Source Apple Doc :

Working with Self-Sizing Table View Cells

In iOS, you can use Auto Layout to define the height of a table view cell; however, the feature is not enabled by default.

Normally, a cell’s height is determined by the table view delegate’s tableView:heightForRowAtIndexPath: method. To enable self-sizing table view cells, you must set the table view’s rowHeight property to UITableViewAutomaticDimension. You must also assign a value to the estimatedRowHeight property. As soon as both of these properties are set, the system uses Auto Layout to calculate the row’s actual height.

Additionally, try to make the estimated row height as accurate as possible. The system calculates items such as the scroll bar heights based on these estimates. The more accurate the estimates, the more seamless the user experience becomes.

关于ios - 自动调整 Tableview 单元格到单元格内容(SWIFT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40114382/

有关ios - 自动调整 Tableview 单元格到单元格内容(SWIFT)的更多相关文章

  1. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  2. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  3. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  4. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  5. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  6. ruby - 查找字符串中的内容类型(数字、日期、时间、字符串等) - 2

    我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s

  7. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  8. ruby-on-rails - Prawn - 表格单元格内的链接 - 2

    我正在尝试用Prawn生成PDF。在我的PDF模板中,我有带单元格的表格。在其中一个单元格中,我有一个电子邮件地址:cell_email=pdf.make_cell(:content=>booking.user_email,:border_width=>0)我想让电子邮件链接到“mailto”链接。我知道我可以这样链接:pdf.formatted_text([{:text=>booking.user_email,:link=>"mailto:#{booking.user_email}"}])但是将这两行组合起来(将格式化文本作为内容)不起作用:cell_email=pdf.make_c

  9. ruby-on-rails - 从应用程序中自定义文件夹内的命名空间自动加载 - 2

    我们目前正在为ROR3.2开发自定义cms引擎。在这个过程中,我们希望成为我们的rails应用程序中的一等公民的几个类类型起源,这意味着它们应该驻留在应用程序的app文件夹下,它是插件。目前我们有以下类型:数据源数据类型查看我在app文件夹下创建了多个目录来保存这些:应用/数据源应用/数据类型应用/View更多类型将随之而来,我有点担心应用程序文件夹被这么多目录污染。因此,我想将它们移动到一个子目录/模块中,该子目录/模块包含cms定义的所有类型。所有类都应位于MyCms命名空间内,目录布局应如下所示:应用程序/my_cms/data_source应用程序/my_cms/data_ty

  10. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

随机推荐