UIView 不根据子视图调整宽度?
Posted
技术标签:
【中文标题】UIView 不根据子视图调整宽度?【英文标题】:UIView not adjusting width according to subviews? 【发布时间】:2017-10-01 09:30:55 【问题描述】:我正在尝试创建一个可重复使用的UIView subclass
,将UILabel
和UIImageView
作为subviews
。我的视图子类应该根据标签的宽度调整它的宽度。
这是我的课-
class CustomView: UIView
private var infoLabel: UILabel!
private var imageView: UIImageView!
override init(frame: CGRect)
super.init(frame: frame)
infoLabel = UILabel(frame: CGRect.zero)
imageView = UIImageView(frame: CGRect.zero)
addSubview(infoLabel)
addSubview(imageView)
infoLabel.backgroundColor = .white
imageView.backgroundColor = .gray
required init?(coder aDecoder: NSCoder)
super.init(coder: aDecoder)
override func updateConstraints()
super.updateConstraints()
infoLabel.translatesAutoresizingMaskIntoConstraints = false
imageView.translatesAutoresizingMaskIntoConstraints = false
infoLabel.leadingAnchor.constraint(
equalTo: self.leadingAnchor, constant: 5).isActive = true
// infoLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
infoLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 5).isActive = true
infoLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 5).isActive = true
imageView.leadingAnchor.constraint(
equalTo: infoLabel.trailingAnchor, constant: 10).isActive = true
//imageView.trailingAnchor.constraint(
//equalTo: self.trailingAnchor, constant: 10).isActive = true
//imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 25).isActive = true
imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 5).isActive = true
imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 5).isActive = true
internal func setText(_ text: String, andImage image: String)
infoLabel.text = text
imageView.image = UIImage(named: image)
这是我将其添加到视图的方式 -
let aView: CustomView = CustomView(frame: CGRect(x: 20, y: 144, width: 120, height: 31))
view.addSubview(aView)
aView.setText("my testing label", andImage: "distanceIcon")
aView.backgroundColor = UIColor.red
我得到了添加图像的结果。(红色是我的自定义视图,白色是标签,灰色是图像)
编辑:如果在 Storyboard 中添加视图,它可以工作,但是如果我通过上面提到的代码尝试它就不能工作。
【问题讨论】:
你是否在 CustomView 上设置了宽度限制? 不,我用框架初始化自定义视图并添加到视图控制器的视图中。(有问题的代码) 您缺少对 imageview 的尾随约束。试试这个:imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 5).isActive = true 试过了,但没有任何区别。 在 addSubview(infoLabel); 之后添加约束代码init 方法中的 addSubview(imageView) 行 【参考方案1】:您还必须在 CustomView 类实例上调用 translatesAutoresizingMaskIntoConstraints = false:
self.translatesAutoresizingMaskIntoConstraints = false
还在自定义视图上添加前导和顶部约束以设置其位置:
customView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 200).isActive = true
customView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 200).isActive = true
不要忘记在 imageView 上添加尾随约束:
imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true
【讨论】:
以上是关于UIView 不根据子视图调整宽度?的主要内容,如果未能解决你的问题,请参考以下文章