I'm trying to make section headers with autolayout. A simple header with a title and a counter
class ProfilePeopleListHeaderViewCell: UIView {
let titleLeftOffset = 12
let counterRightOffset = 5
let counterWidth = 50
var title = "title" {
didSet {
titleLabel.text = title
}
}
var numberOfPeople = 0 {
didSet {
peopleCounter.text = "\(numberOfPeople)"
}
}
let titleLabel = UILabel()
let peopleCounter = UILabel()
convenience init(title: String, numberOfPeople:Int) {
self.init()
self.title = title
self.numberOfPeople = numberOfPeople
backgroundColor = UIColor.greenColor()
titleLabel.textColor = Constants.Colors.ThemeGreen
titleLabel.textAlignment = .Left
if #available(iOS 8.2, *) {
titleLabel.font = Constants.Fonts.Profile.PeopleListHeaderFont
peopleCounter.font = Constants.Fonts.Profile.PeopleListHeaderFont
} else {
titleLabel.font = UIFont.systemFontOfSize(14)
peopleCounter.font = UIFont.systemFontOfSize(14)
}
peopleCounter.textAlignment = .Right
peopleCounter.textColor = Constants.Colors.ThemeDarkGray
addSubview(titleLabel)
addSubview(peopleCounter)
self.titleLabel.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(self)
make.height.equalTo(self)
make.width.equalTo(peopleCounter).multipliedBy(3)
make.left.equalTo(self).offset(titleLeftOffset)
}
self.peopleCounter.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(self)
make.height.equalTo(self)
make.width.equalTo(counterWidth)
make.left.equalTo(titleLabel.snp_right)
make.right.equalTo(self).offset(counterRightOffset)
}
}
}
The code to retrieve the header is:
let mutualFriendsSectionView = ProfilePeopleListHeaderViewCell(title: Strings.Title.MutualFriends, numberOfPeople: 0)
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 1 {
//mutualFriendsSectionView.layoutSubviews()
return mutualFriendsSectionView
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
I get a green background in the section header. But I don't see any label...
Actually it's working. my mistake was to believe that didSet{} was also called within the class -> it's not the case.
When I was setting the title in the init() it was not setting the label text.