【发布时间】:2021-04-21 07:28:03
【问题描述】:
我正在尝试创建 tableView 单元格并自定义布局。但似乎我在单元格中添加的任何内容都被卡在与单元格本身相同大小的高度和宽度上。我怎样才能到达我可以设计我喜欢的细胞的地方?即,使我的图像具有边距和填充的特定尺寸。甚至我的文本高度也被拉伸到单元格高度。我添加了边框,以便我的意思可见。我的标签的高度应该只是文本本身的大小,但它仍在拉伸。
我被困在 tableview 单元格上,想要完全以编程方式设计我的单元格布局,而无需故事板。我整天都在努力自学,然后继续兜圈子。
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(self.tableView)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.frame = view.bounds
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 8
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Here is some text"
cell.textLabel?.layer.cornerRadius = 10
cell.textLabel?.layer.borderWidth = 5
cell.textLabel?.layer.borderColor = UIColor.black.cgColor
cell.imageView?.image = UIImage(named: "spiderman")!
cell.imageView?.layer.cornerRadius = 10
cell.imageView?.layer.borderWidth = 5
cell.imageView?.layer.borderColor = UIColor.black.cgColor
return cell
}
}
【问题讨论】:
-
为此请移除 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 200 }。从代码。其设置Cell的静态高度。在 Storyboard 中为您的单元格组件提供高度。
-
我的故事板中没有单元格。我以编程方式完成了这一切。这是唯一的方法吗?我没有碰过故事板。
-
因此,当您以编程方式设置单元格项目时,请提供它们的高度。
-
那个也不行,图片和txt和单元格高度一样
-
即使我想改变我的 txt 或图像的位置,也没有任何移动
标签: swift uitableview tableview cell