I’m trying to make a UIImage View in table view cell to a perfect circle by code in Swift.
At first, I put img.layer.cornerRadius = 35
in my code and it makes my image almost like a circle. Then instead of passing a number to the corner radius, I was trying to write that part by code, something like img.layer.cornerRadius = img.frame.height / 2
. However, this code makes the UIImage square (doesn’t apply corner radius). I am not sure why this happens. Could anyone please explain why this happens and how to fix it?
class RepositoryCell: UITableViewCell {
let userImageView: UIImageView = {
let img = UIImageView()
img.contentMode = .scaleAspectFit
img.layer.cornerRadius = img.frame.height / 2
// img.layer.cornerRadius = 35 <= this code works
img.clipsToBounds = true
img.backgroundColor = .black
return img
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(userImageView)
containerView.addSubview(userNameLabel)
containerView.addSubview(repositoryNameLabel)
addSubview(containerView)
addSubview(starNumLabel)
configureViewComponents()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureViewComponents() {
setUserImageConstraints()
}
func setUserImageConstraints() {
userImageView.translatesAutoresizingMaskIntoConstraints = false
userImageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
userImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
userImageView.heightAnchor.constraint(equalToConstant: 80).isActive = true
userImageView.widthAnchor.constraint(equalTo: userImageView.heightAnchor, multiplier: 1).isActive = true
}
2
Answers
Because
let img = UIImageView()
->frame == zero
You can do like this:
if you use RxSwift, you can simply call
img.cornerHalf()
,it uses Key Path Observe
with the assist code below