как получить круглый UIbutton в tableviewcell в Swift? - PullRequest
0 голосов
/ 11 октября 2018
class CustomTableViewCell: UITableViewCell {
let nameLbl: UILabel = UILabel()
let profileBtn: UIButton = UIButton()
let aboutLbl: UILabel = UILabel()


override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    contentView.addSubview(profileBtn)
    contentView.addSubview(nameLbl)
    contentView.addSubview(aboutLbl)

    nameLbl.translatesAutoresizingMaskIntoConstraints = false
    profileBtn.translatesAutoresizingMaskIntoConstraints = false
    aboutLbl.translatesAutoresizingMaskIntoConstraints = false


    profileBtn.backgroundColor = UIColor.red

    nameLbl.font = UIFont(name: "Arial", size: 16)
    aboutLbl.font = UIFont(name: "Arial", size: 16)
    profileBtn.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    profileBtn.leftAnchor.constraint(equalTo: leftAnchor, constant: 20).isActive = true
    profileBtn.widthAnchor.constraint(equalToConstant: 40).isActive = true
    profileBtn.heightAnchor.constraint(equalToConstant: 40).isActive = true
    self.profileBtn.layer.masksToBounds = true
    self.profileBtn.layer.cornerRadius  = CGFloat(roundf(Float(self.profileBtn.frame.size.width/2.0)))

    nameLbl.topAnchor.constraint(equalTo: topAnchor, constant: 30).isActive = true
    nameLbl.leftAnchor.constraint(equalTo: leftAnchor, constant: 70).isActive = true
    nameLbl.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true

    aboutLbl.topAnchor.constraint(equalTo: nameLbl.bottomAnchor, constant: 10).isActive = true
    aboutLbl.leftAnchor.constraint(equalTo: leftAnchor, constant: 70).isActive = true
    aboutLbl.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true


}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

Я хочу, чтобы кнопка профиля внутри ячейки имела круглую форму. Но ebven, устанавливающая радиус ядра и основные ограничения на true, получает квадратную кнопку.Что я делаю не так, любая помощь приветствуется.заранее спасибо.

Ответы [ 3 ]

0 голосов
/ 11 октября 2018

При инициализации ячейки кнопка не имеет рамки.Таким образом, self.profileBtn.layer.cornerRadius = CGFloat(roundf(Float(self.profileBtn.frame.size.width/2.0))) приводит к cornerRadius, равному 0.

Поскольку вы задаете 40 постоянную ширину и высоту для кнопки, вы можете просто сделать это:

self.profileBtn.layer.cornerRadius  = 20.0

Также обязательно установите кнопку для ограничения границ:

self.profileBtn.clipsToBounds = true
0 голосов
/ 11 октября 2018

Вот мое решение:

override func layoutSubviews() {
    super.layoutSubviews()

    self.makeItCircle()
}

func makeItCircle() {
    self.yourbutton.layer.masksToBounds = true 
    self.yourbutton.layer.cornerRadius  = CGFloat(roundf(Float(self.yourbutton.frame.size.width/2.0)))
}

self.imageView.layer.masksToBounds = true  //- in main 
0 голосов
/ 11 октября 2018

Вы рассчитываете угловой радиус, когда кнопка профиля еще не выложена.Это означает, что ширина кнопки профиля будет равна нулю, оставляя радиус угла одинаковым.Переместите линию, в которой вы устанавливаете радиус угла, на метод переопределения layoutSubviews - это обеспечит расположение видов и последующих размеров, чтобы вы могли установить соответствующий радиус угла.

override func layoutSubviews() {

    super.layoutSubviews()

    profileBtn.layer.cornerRadius = profileBtn.frame.width / 2
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...