gpt4 book ai didi

Swift:UIButton edgeinsets 在单元格重绘/滚动后应用

转载 作者:可可西里 更新时间:2023-11-01 01:59:53 24 4
gpt4 key购买 nike

经过几天的挣扎,我想问你有关 UIButton 标题和图像边缘插入的问题......我有带按钮的自定义单元格,该按钮取决于单元格类型应该是不同的图标和文本,但要求文本应该居中,图像可以左对齐或右对齐。为此,我在更新按钮图 block 和图像期间设置了边缘插入。为简单起见,我将图像插入左侧硬编码为 8,并计算文本应从其开始的标题左侧点。

func setTitleWithImage(_ title: String, imageName: String) {
self.btnStatus.setTitle(title, for: .normal)
self.btnStatus.setImage(UIImage(named: imageName), for: .normal)

self.btnStatus.imageEdgeInsets.left = 8
let btnWidth = btnStatus.frame.width
let titleLabelWidth = btnStatus.titleLabel?.frame.width
self.btnStatus.titleEdgeInsets.left = (btnWidth / 2) - (titleLabelWidth! / 2) - (btnStatus.imageView?.frame.width)! + self.btnStatus.imageEdgeInsets.left
}

问题是,当加载 tableview 时它对齐错误,但在滚动/重绘单元格后它对齐正确。我尝试了不同的建议,但没有人帮助我。

滚动前

Before Scroll

滚动后

After scroll

在这里更具体地说是整个项目。

Sources

已更新

ViewController几乎全部,更详细请下载源码

   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 140
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomTableViewCell
cell.setTitleWithImage("DIFFERENT TEXT IS HERE ?", imageName: "icon")
cell.layoutIfNeeded()
cell.setNeedsLayout()


return cell
}

最佳答案

func alignTitleWithImageFrames () {
let btnWidth = btnStatus.frame.width
let titleLabelWidth = btnStatus.titleLabel?.frame.width
self.btnStatus.titleEdgeInsets.left = (btnWidth / 2) - (titleLabelWidth! / 2) - (btnStatus.imageView?.frame.width)! + 13
self.btnStatus.imageEdgeInsets.left = 8
}

关于Swift:UIButton edgeinsets 在单元格重绘/滚动后应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47577665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com