我有一个UIImageView,并以编程方式向其添加了约束。位置是正确的,但是从屏幕截图中可以看到,它可以伸展我的图像...这是我的限制条件:
let arrow = UIImageView()
contentView.addSubview(arrow)
arrow.translatesAutoresizingMaskIntoConstraints = false
arrow.widthAnchor.constraint(equalToConstant: 25).isActive = true
arrow.heightAnchor.constraint(equalToConstant: 25).isActive = true
arrow.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor).isActive = true
arrow.topAnchor.constraint(equalTo: marginGuide.topAnchor).isActive = true
arrow.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor).isActive = true
我的问题是我在这里做错了什么?
答案 0 :(得分:1)
不一定总要给出所有约束(例如前导,尾随,顶部,底部,高度,宽度等)来定义其相对于其概览的大小。
视图只需要一个必要的约束即可在其超级视图中设置其坐标。
正如rmaddy所说,不要对视图施加过多约束。
您只需要以下常量(只需删除所有其他约束)
arrow.widthAnchor.constraint(equalToConstant: 25).isActive = true
arrow.heightAnchor.constraint(equalToConstant: 25).isActive = true
contentView.centerYAnchor.constraint(equalTo: arrow.centerYAnchor).isActive = true
arrow.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor).isActive = true
答案 1 :(得分:0)
该底部锚点导致拉伸图像。您有多种选择:
通常,使用自动像元高度时,应该从上到下连接的视图是单元的标签或最后一个底视图。
答案 2 :(得分:0)
您应该添加垂直居中约束,并在不需要时移除顶部和底部锚点
let arrow = UIImageView()
contentView.addSubview(arrow)
arrow.translatesAutoresizingMaskIntoConstraints = false
arrow.widthAnchor.constraint(equalToConstant: 25).isActive = true
arrow.heightAnchor.constraint(equalToConstant: 25).isActive = true
arrow.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor).isActive = true
let yConstraint = NSLayoutConstraint(item: arrow, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([yConstraint]) //Or contentView.centerYAnchor.constraint(equalTo: arrow.centerYAnchor).isActive = true
,或者您的单元格固定高度
arrow.topAnchor.constraint(equalTo: marginGuide.topAnchor, constant: 25).isActive = true // 25 or space your design need
arrow.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor, constant: 25).isActive = true //25 or space your design need need