gpt4 book ai didi

ios - sizeToFit 不适用于编程表格 View 单元格

转载 作者:行者123 更新时间:2023-11-28 15:53:02 25 4
gpt4 key购买 nike

我有一个基本的自定义单元格,左侧有一个名称标签,右侧有一个价格标签,它们都设置在另一个 View 中以自定义间距。我希望价格将宽度更改为任何价格并且没有设置它但是当我在单元格 init 或 cellForRow 的价格上使用 sizetofit 时,什么也没有发生。我环顾四周,但看不出如何让它发挥作用。在单元格的初始化中我无法获得文本大小,但在 cellForRowAt 中设置标签大小似乎不正确。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell: SplitterCarouselItemTableViewCell = tableView.dequeueReusableCell(withIdentifier: "splitterCarouselItemTableViewCell") as! SplitterCarouselItemTableViewCell
var item = ((allBillSplitters[tableView.tag].items)?.allObjects as! [Item])[indexPath.row]
if allBillSplitters[tableView.tag].isMainBillSplitter {
getMainBillSplitterItems(splitter: allBillSplitters[tableView.tag])
item = mainBillSplitterItems[indexPath.row]
}
let count = item.billSplitters?.count

if count! > 1 {
cell.name!.text = "\(item.name!)\nsplit \(count!) ways"
cell.price!.text = "£\(Double(item.price)/Double(count!))"

} else {
cell.name!.text = item.name!
cell.price!.text = "£\(item.price)"
}

return cell
}

这是我的手机:

import UIKit

class SplitterCarouselItemTableViewCell: UITableViewCell {

var name: UILabel!
var price: UILabel!
var view: UIView!

required init(coder aDecoder: NSCoder) {
fatalError("init(coder:)")
}

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

self.setupViews()
}

func setupViews() {

let width = Int(UIScreen.main.bounds.width * 0.88)
let height = Int(self.bounds.height)

self.backgroundColor = .clear
self.frame = CGRect(x: 0, y: 0, width: width, height: 45)

view = UIView(frame: CGRect(x: 0, y: 2, width: width, height: height - 4 ))
view.backgroundColor = UIColor.white.withAlphaComponent(0.5)

price = UILabel(frame: CGRect(x: width - 80, y: 0, width: 75, height: height))
price.font = UIFont.systemFont(ofSize: 15.0)
price.backgroundColor = .yellow
price.textAlignment = .right

name = UILabel(frame: CGRect(x: 5, y: 0, width: Int(price.frame.width), height: height))
name.backgroundColor = .red
name.font = UIFont.systemFont(ofSize: 15.0)
name.numberOfLines = 0

view.addSubview(name)
view.addSubview(price)

contentView.addSubview(view)
}
}

任何帮助都会很棒,我确定我缺少一些基本的东西。

我添加了黄色和红色背景以便在屏幕截图中可见。

Screen Shot

最佳答案

您需要根据文本计算价格标签的宽度。下面的代码将帮助您找到宽度

extension String {
func widthWithConstrainedHeight(height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height )
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

return boundingBox.width
}
}

使用上述函数查找字符串宽度并使用该宽度创建价格标签的框架。

关于ios - sizeToFit 不适用于编程表格 View 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42098289/

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