【问题标题】:swift: how to use constraints with multiplier in codeswift:如何在代码中使用带乘数的约束
【发布时间】:2019-08-08 02:39:16
【问题描述】:

我有一个自定义视图,我想添加一个图像,使其底部锚点位于视图的 3/4。在情节提要中,我只需使用第一项 imgview.bottom、第二项 view.bottom、常量 0 和乘数 0.75 设置一个约束

在我尝试过的代码中:

let imgview = UIImageView(image: img)
imgview.translatesAutoresizingMaskIntoConstraints = false
addSubview(imgview)
NSLayoutConstraint.activate([
    imgview.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.4),
    imgview.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.4),
    imgview.centerXAnchor.constraint(equalTo: centerXAnchor),
    imgview.bottomAnchor.constraint(equalToSystemSpacingBelow: bottomAnchor, multiplier: 0.75)
    ])

但图像的底部甚至低于视图的底部。 如果我使用bottomAnchor.constraint(equalToSystemSpacingBelow: imgview.bottomAnchor, multiplier: 0.75)

它高于它,但仍然太低。我该怎么做?

【问题讨论】:

  • imgviewcontentMode 是什么?你可能需要做imgview.clipsToBounds = true

标签: swift


【解决方案1】:

我会使用equalTo:,constant: 来完成它。

let frameHeight = frame.height
let padding = frameHeight * 0.25
imgview.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -padding)

如果视图尚未加载,帧值可能会返回 0。

override func layoutSubviews() {
super.layoutSubviews()
if self.frame.height > 0 {
//Add constraints here
}
}

【讨论】:

    【解决方案2】:

    以老式方式为最后一个使用约束创建:

    let imgview = UIImageView(image: img)
    imgview.translatesAutoresizingMaskIntoConstraints = false
    addSubview(imgview)
    NSLayoutConstraint.activate([
        imgview.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.4),
        imgview.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.4),
        imgview.centerXAnchor.constraint(equalTo: centerXAnchor),
    /// imgview.bottomAnchor.constraint(equalToSystemSpacingBelow: bottomAnchor, multiplier: 0.75)
        ])
    
    let constraint = NSLayoutConstraint(item: imgview, attribute: .bottom, 
                                        relatedBy: .equal, 
                                        toItem: view, attribute: .bottom, 
                                        multiplier: 0.75, constant: 0)
    constraint.isActive = true
    

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 2015-12-03
      • 1970-01-01
      • 2019-01-14
      • 2022-11-17
      • 2016-11-29
      • 2015-08-01
      • 1970-01-01
      • 2017-12-07
      相关资源
      最近更新 更多