【发布时间】:2021-04-09 08:46:36
【问题描述】:
我需要实现一个保存按钮。当用户点击按钮时,它必须被填充,默认情况下它是未填充的。但是当我运行我的应用程序时,tableView 单元格中的一些按钮已经填满like that
这是来自 TableViewCell 的代码
var isFavorite: Bool = false
private let addToFavorites: UIButton = {
let button = UIButton(type: .custom)
button.setImage(UIImage(systemName: "heart"), for: .normal)
button.tintColor = UIColor.white.withAlphaComponent(0.85)
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
return button
}()
override func awakeFromNib() {
super.awakeFromNib()
setFavoriteButtonUI()
addToFavorites.addTarget(self, action: #selector(markFavorite), for: .touchUpInside)
}
@objc func markFavorite() {
setFavoriteButtonImage()
}
private func setFavoriteButtonImage() {
isFavorite = !isFavorite
let imgName = isFavorite ? "heart" : "heart.fill"
let favoriteButtonImage = UIImage(systemName: imgName)
self.addToFavorites.setImage(favoriteButtonImage, for: .normal)
}
private func setFavoriteButtonUI() {
addToFavorites.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(addToFavorites)
addToFavorites.topAnchor.constraint(equalTo: filmImgView.topAnchor, constant: 40).isActive = true
addToFavorites.trailingAnchor.constraint(equalTo: filmImgView.trailingAnchor, constant: -20).isActive = true
addToFavorites.heightAnchor.constraint(equalToConstant: 30).isActive = true
addToFavorites.widthAnchor.constraint(equalToConstant: 40).isActive = true
}
在我添加的 cellForRowAt indexPath 方法中
tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.top)
【问题讨论】:
标签: swift uitableview uibutton