I’m following a tutorial for a messaging chat app and I keep getting errors on the UIImageViews. For example ~ userImageView.right, userImageView.width, etc. all get errors saying UIImageView has no member. I’ve used the right/width/height in other parts of my app, I can’t figure out why it’s not happy here… thoughts?
class ConversationTableViewCell: UITableViewCell {
static let identifier = "ConversationTableViewCell"
private let userImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.layer.cornerRadius = 50
imageView.layer.masksToBounds = true
return imageView
}()
private let userNameLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 21, weight: .semibold)
return label
}()
private let userMessageLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 19, weight: .regular)
label.numberOfLines = 0
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(userImageView)
contentView.addSubview(userNameLabel)
contentView.addSubview(userMessageLabel)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
userImageView.frame = CGRect(x: 10,
y: 10,
width: 100,
height: 100)
userNameLabel.frame = CGRect(x: userImageView.right + 10,
y: 10,
width: contentView.width - 20 - userImageView.width,
height: (contentView.height-20)/2)
userMessageLabel.frame = CGRect(x: userImageView.right + 10,
y: userNameLabel.bottom + 10,
width: contentView.width - 20 - userImageView.width,
height: (contentView.height-20)/2)
}
2
Answers
A
UIImageView
is aUIView
object. As such it has a frame property, which is aCGRect
.You can use
someImageView.frame
to get to the view’s frame.CGRect
s have propertiessize.height
andsize.width
. They also have propertiesmaxX
andmaxY
, which are equivalent toright
andbottom
. (actually, it seemsCGRect
also has propertiesheight
andwidth
, so you can skip the "size." prefix.)So for an imageView
someImageView
:If you want you could add an extension to UIView that added the properties height, width, right, and bottom as in @afaq’s answer. (Voted)
Create a new swift file and add following code in that and everything will be good to go.
Or:
More easy way to just import this package AATools in your project, it contains many handy extensions for speedy development.