I’m trying to make a custom header for 0 section of my UITableView. Here’s the code I’m using to create this header:
class ProfileHeaderView: UITableViewHeaderFooterView {
// MARK: - Subviews
private var statusText: String = ""
private lazy var userImage: UIImageView = {
let imageView = UIImageView(image: UIImage(named: me.login))
imageView.layer.cornerRadius = 48
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
...
// MARK: - Lifecycle
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
setupUI()
addSuviews()
setupConstraints()
}
// MARK: - Private
private func setupUI() {
backgroundColor = .lightGray
}
private func addSuviews() {
addSubview(userImage)
}
private func setupConstraints() {
let layoutMarginGuide = contentView.layoutMarginsGuide
NSLayoutConstraint.activate([
userImage.leadingAnchor.constraint(equalTo: layoutMarginGuide.leadingAnchor, constant: 10),
userImage.topAnchor.constraint(equalTo: layoutMarginGuide.topAnchor, constant: 16),
userImage.bottomAnchor.constraint(equalTo: layoutMarginGuide.bottomAnchor, constant: -16),
userImage.widthAnchor.constraint(equalToConstant: 90),
userImage.heightAnchor.constraint(equalToConstant: 90),
])
}
}
Here’s how I add this header in my ViewController:
private func setupConstraints() {
feedView.frame = view.bounds
feedView.delegate = self
feedView.dataSource = self
feedView.register(PostViewCell.self, forCellReuseIdentifier: "cell")
feedView.register(ProfileHeaderView.self, forHeaderFooterViewReuseIdentifier: "ProfileHeaderView")
//feedView.register(ProfileHeaderView.self, forHeaderFooterViewReuseIdentifier: "profileView")
}
Here’s the result I’m getting:
As you see, image is ignoring safeArea on the screen. How to fix it?
2
Answers
Use
contentView.safeAreaLayoutGuide
instead ofcontentView.layoutMarginsGuide
as your layout guide.safeAreaLayoutGuide
represents the layout area in between bars (e.g the layout between the status bar and the home bar)EDIT: It probably makes more sense to correctly set the constraints of your table view (using the
safeAreaLayoutGuide
) instead of having to do that for individual views within your table viewWell, you left out much of the needed code (such as your cell class and your controller class).
And, you haven’t shown your code for
viewForHeaderInSection
.But, we can look at a quick example…
your
ProfileHeaderView
with minor modificationsa simple single-label cell class
a simple view controller class with table view – number of rows set to 30 so we can see the section header stays in place…
Looks like this when run: