Я разрабатываю приложение для iOS в Swift, и у меня есть UITableView
с пользовательским UITableViewCells
, который имеет интервал слева и справа от ячейки путем переопределения layoutSubviews()
.
.вычитая от 40 до self.bounds.size.width
.
Поскольку я не очень хорош в объяснении, здесь у вас есть изображение:
Но проблема в том, что когда я щелкаю по ячейке, перезапущенная функция layoutSubviews()
запускается снова, поэтому ячейка снова сокращается, поскольку она снова вычитает 40 из уже оригинала self.bounds.size.width - 40
.
Как можно избежать запуска layoutSubviews()
при каждом щелчке по ячейке и запускать его только один раз при загрузке представления?
Я не знаю, почему layoutSubviews запускается снова, так как он загружен в мой пользовательский класс UITableViewCell.
Здесь у вас есть мой код:
class TBRepoTableViewCell: UITableViewCell {
@IBOutlet weak var repoLabel: UILabel!
@IBOutlet weak var urlLabel: UILabel!
@IBOutlet weak var repoIcon: UIImageView!
override func layoutSubviews() {
// Set the width of the cell
self.bounds = CGRect(self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width - 40, self.bounds.size.height)
super.layoutSubviews()
}
}
class SourcesViewController: UITableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// note that indexPath.section is used rather than indexPath.row
print("You tapped cell number \(indexPath.row).")
}
override func viewWillAppear(_ animated: Bool) {
setEditing(false, animated: true)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TBRepoTableViewCell
let repoArray = array[indexPath.row]
cell.repoLabel.text = repoArray.repoName
cell.urlLabel.text = repoArray.repoURL
cell.repoIcon.image = repoArray.icon
self.tableView.separatorStyle = .none
// add borders
cell.layer.cornerRadius = 10
cell.clipsToBounds = true
cell.layer.masksToBounds = true
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
array.remove(at: indexPath.row)
tableView.reloadData()
}
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
}