在自定义表格单元格内使用约束进行 Swift UIKit 排序和定位

问题描述 投票:0回答:1

我有一个自定义表格单元格,我想做的就是在其中插入两个按钮图像。这是我的代码:

gb = UIButton()
gb.setImage(UIImage(named: "skejt_zelena_polutka"), for: .normal)
gb.frame.size = CGSize(width: 40.0, height: 30.0)
            
rb = UIButton()
rb.setImage(UIImage(named: "skejt_crvena_polutka"), for: .normal)
rb.frame.size = CGSize(width: 40.0, height: 30.0)
            
self.isUserInteractionEnabled = true
            
contentView.addSubview(gb)
contentView.addSubview(rb)
            
contentView.layer.borderColor = .init(red: 0, green: 0, blue: 0, alpha: 1)
contentView.layer.borderWidth = 2
            
gb.leftAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leftAnchor, constant: 0).isActive = true
gb.layer.borderColor = .init(red: 0, green: 255, blue: 0, alpha: 1)
gb.layer.borderWidth = 2
            
rb.leftAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leftAnchor, constant: 140).isActive = true
rb.rightAnchor.constraint(equalTo: contentView.layoutMarginsGuide.rightAnchor, constant: 0).isActive = true
rb.layer.borderColor = .init(red: 255, green: 0, blue: 0, alpha: 1)
rb.layer.borderWidth = 2

但我只显示 rb,而不是两者。另外,rb 与 contentView 左侧的边距没有 140。我还尝试将 rb 的 leftAnchor 限制为 rb 的 rightAnchor:

rb.leftAnchor.constraint(equalTo: gb.rightAnchor, constant: 140).isActive = true

结果相同。我尝试省略layoutMarginsGuide,结果相同。我在这里缺少什么?

swift uikit constraints custom-cell
1个回答
0
投票

添加

contentView.translatesAutoresizingMaskIntoConstraints = false
rb.translatesAutoresizingMaskIntoConstraints = false
gb.translatesAutoresizingMaskIntoConstraints = false

解决了问题。

© www.soinside.com 2019 - 2024. All rights reserved.