【问题标题】:How do I set constraint for textLabel and detailTexLabel of UITableViewCell如何为 UITableViewCell 的 textLabel 和 detailTexLabel 设置约束
【发布时间】:2019-03-15 00:44:49
【问题描述】:

我也想做同样的事情,将定义明确的约束从左侧放置到 UITableViewCell 元素。

var cell = tableView.dequeueReusableCell(withIdentifier: "Starred")
if cell == nil {
    cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Starred") 
}
return cell!

【问题讨论】:

    标签: ios swift xcode uitableview cocoa-touch


    【解决方案1】:

    试试这个,就我而言,我调整了 textLabel 和 imageView 的大小

    import UIKit
    class TableViewCellClass: UITableViewCell {
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if UIDevice().userInterfaceIdiom == .pad {
            //Here change your detailedTextLabel
            imageView?.frame = CGRect(x: 25, y: 15.0, width: 25, height: 25)//Change left menu table view image size
            imageView?.contentMode = UIViewContentMode.scaleAspectFit
            textLabel?.frame = CGRect(x: 70, y: 12.5, width: 250, height: 30)//Change left menu table view text label size
        } else {
            //Here change your detailedTextLabel
            imageView?.frame = CGRect(x: 15, y: 12.5, width: 25, height: 25)//Change left menu table view image size
            imageView?.contentMode = UIViewContentMode.scaleAspectFit
            textLabel?.frame = CGRect(x: 60, y: 12.5, width: 200, height: 25)//Change left menu table view text label size
        }
    }
    

    【讨论】:

    • 是否可以更改 backgroundView 框架或类似 backgroundView?.translatesAutoresizingMaskIntoConstraints = false 然后使用锚约束?这两种方法我都试过了,都不管用。
    【解决方案2】:

    我发现在这种情况下可以通过编程方式布局您的自定义单元格。

    另外,为了保持 ViewController 精简,创建自定义单元格的子类并重写将 .subtitle 作为样式传递的 init 方法。

    例子:

    class StarCell: UITableViewCell {
         override init(style: UITableViewCellStyle, resuseIdentifier: String?) {
             super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
    
             self.detailTextLabel?.translatesAutoresizingMaskIntoConstraints = false
             self.detailTextLabel?.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
             self.detailTextLabel?.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
             self.detailTextLabel?.heightAnchor.constraint(equalToConstant: 30).isActive = true
    
             self.detailTextLabel.text = "Testing Subtitle"
         }
    }
    

    textLabel 几乎相同。不要忘记将 autoresizingMaskIntoConstraints 设置为 false,因为它是 false,所以您必须设置高度或宽度,否则标签将不会呈现。如果您希望标签高度根据屏幕尺寸变化,您可以在设置约束时使用 multiplier 参数。

    注意。 Xcode 会抱怨需要所需的 init 方法,只需单击红点并修复。 Xcode 会自动为你插入代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      相关资源
      最近更新 更多