마지막으로 TableView의 헤더를 구현해보자
여기서는 마이프로필 즉 친구뷰 중에서 자기를 표현하는 부분을 헤더로 구현할 것이다.
그림으로 보면 아래와 같다!
import Foundation
import UIKit
import SnapKit
import SwiftyColor
import Then
final class FriendHeaderView: UITableViewHeaderFooterView { //중요중요!!!
//MARK: - Properties
static let identifier = "FriendHeaderView" // 꼭!!!! identifier 선언!!
//MARK: - UI Components
private let profileImageView = UIImageView().then{
$0.image = Image.friendProfileImage
}
private let profileNameLabel = UILabel().then {
$0.text = "김솝트"
$0.font = UIFont(name: "AppleSDGothicNeo-SemiBold", size: 16)
$0.textColor = 0x191919.color
}
private let profileMessageLabel = UILabel().then {
$0.text = "상태메시지는 여기에"
$0.font = UIFont(name: "AppleSDGothicNeo-Regular", size: 11)
$0.textColor = 0xA6A6A6.color
}
//MARK: - Life Cycle
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
setupView()
setupConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Custom Method
private func setupView() {
contentView.backgroundColor = .white
[profileImageView, profileNameLabel, profileMessageLabel].forEach {
contentView.addSubview($0)
}
}
private func setupConstraints() {
profileImageView.snp.makeConstraints {
$0.top.equalToSuperview().offset(7)
$0.leading.equalToSuperview().offset(16)
$0.width.equalTo(59)
$0.height.equalTo(58)
}
profileNameLabel.snp.makeConstraints {
$0.top.equalToSuperview().offset(19)
$0.leading.equalTo(self.profileImageView.snp.trailing).offset(11)
}
profileMessageLabel.snp.makeConstraints {
$0.top.equalTo(self.profileNameLabel.snp.bottom).offset(6)
$0.leading.equalTo(self.profileNameLabel)
}
}
}
테이블뷰에 헤더를 등록해야겠죠?
private func register() {
friendView.friendTableView.register(
FriendTableViewCell.self, forCellReuseIdentifier: FriendTableViewCell.identifier)
friendView.friendTableView.register(
FriendHeaderView.self, forHeaderFooterViewReuseIdentifier: FriendHeaderView.identifier)
}
테이블뷰에 등록된 셀이 어떤 친군지 알려주기 위해서 UITableViewDelegate와 UITableViewDataSource를 사용했자나요?
테이블뷰 헤더뷰 또한 어떤 친군지 설명을 해줘야하는데요!
UITableViewDelegate를 통해서 이 친구의 높이와 어떤 뷰인지 설명해줄꺼에요!
extension FriendView: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 73
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let headerView = tableView.dequeueReusableHeaderFooterView(
withIdentifier: FriendHeaderView.identifier)
as? FriendHeaderView else { return UIView() }
return headerView
}
}