iOS Swift scrolled tableview image background
import UIKit
import TPKeyboardAvoiding
class CustomTableView: TPKeyboardAvoidingTableView {
lazy var imageViewBgHeader: UIImageView = {
let imageViewBgHeader = UIImageView()
imageViewBgHeader.image = kImg.bgHeaderHome.image
imageViewBgHeader.contentMode = .scaleAspectFill
imageViewBgHeader.isUserInteractionEnabled = false
imageViewBgHeader.clipsToBounds = true
return imageViewBgHeader
}()
var constraintImageWidth: NSLayoutConstraint?
override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
func setupView() {
let imageRatio: CGFloat = (2 / 3)
let viewHeight = UIScreen.main.bounds.width * imageRatio
var topMargin: CGFloat = 0
if UIDevice.current.hasTopNotch {
topMargin = -64
}
self.addSubview(imageViewBgHeader)
self.translatesAutoresizingMaskIntoConstraints = false
imageViewBgHeader.translatesAutoresizingMaskIntoConstraints = false
imageViewBgHeader.topAnchor.constraint(
equalTo: self.topAnchor, constant: topMargin).isActive = true
imageViewBgHeader.leftAnchor.constraint(
equalTo: self.leftAnchor).isActive = true
imageViewBgHeader.rightAnchor.constraint(
equalTo: self.rightAnchor).isActive = true
imageViewBgHeader.heightAnchor.constraint(
equalToConstant: viewHeight).isActive = true
imageViewBgHeader.layer.zPosition = -1000
constraintImageWidth = imageViewBgHeader.widthAnchor.constraint(
equalToConstant: UIScreen.main.bounds.width)
constraintImageWidth?.isActive = true
}
override func layoutSubviews() {
super.layoutSubviews()
DispatchQueue.main.async { [unowned self] in
self.constraintImageWidth?.constant = UIScreen.main.bounds.width
self.imageViewBgHeader.layoutIfNeeded()
}
}
}