我有一个自定义表格单元格,我想做的就是在其中插入两个按钮图像。这是我的代码:
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,结果相同。我在这里缺少什么?
添加
contentView.translatesAutoresizingMaskIntoConstraints = false
rb.translatesAutoresizingMaskIntoConstraints = false
gb.translatesAutoresizingMaskIntoConstraints = false
解决了问题。