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

标签 swift uitableview uibutton padding uiedgeinsets

经过几天的挣扎,我想问你有关 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/

相关文章:

ios - 如何在生产中获得原始应用程序版本?

swift - 如何在 UITableViewCell swift 中获取 UIView 的正确宽度

ios - UITableView 不显示 IOS 7 中的单元格

ios - 转到不同 UITableViewCell 中的下一个 UITextField

ios - 点击时使 UIButton 文本变暗

ios - 使用 CABasicAnimation 移动时无法使用 UIButton

ios - 适当的更改不会影响表格 View 部分标题背景

ios - 将数据从 SettingsView Controller 传递到 Mainstoryboard - Swift

Swift:面向协议(protocol)的方法期间出错。错误:无法将类型 'I.Job' 的返回表达式转换为返回类型 'ActualJob'

iOS 子类 UIView - 如何从 ViewController 调用 UIButton 方法?