1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| import UIKit
class ViewController: UIViewController { private lazy var tableView: UITableView = { let tableView = UITableView(frame: .zero, style: .plain) tableView.delegate = self tableView.dataSource = self tableView.tableHeaderView = tableHeaderView tableView.translatesAutoresizingMaskIntoConstraints = false tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CELL") return tableView }() private lazy var tableHeaderView: UIView = { let avatarImageView: UIImageView = { let imageView = UIImageView(image: UIImage(systemName: "person.circle")) imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() let nameLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.text = "洛阳城里见秋风,欲作家书意万重" label.translatesAutoresizingMaskIntoConstraints = false return label }() let view = UIView(frame: CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: 150))) view.addSubview(avatarImageView) view.addSubview(nameLabel) NSLayoutConstraint.activate([ avatarImageView.widthAnchor.constraint(equalToConstant: 50), avatarImageView.heightAnchor.constraint(equalToConstant: 50), avatarImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor), avatarImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16), nameLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor), nameLabel.leadingAnchor.constraint(equalTo: avatarImageView.trailingAnchor, constant: 12), nameLabel.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -16), ]) return view }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), ]) } }
extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CELL", for: indexPath) cell.textLabel?.text = "\(indexPath.row)" return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print(indexPath) } }
|