调整UIImageView的大小并进行约束

时间:2018-12-11 16:38:13

标签: ios swift constraints

我想让我的应用以编程方式调整UIImageView或UIbutton的大小吗?

我已经尝试过了

let imageView = UIImageView(frame: CGRect(x: self.view.center.x, y: self.view.center.y + 400, width: self.view.frame.maxX - 100, height: self.view.frame.midY - 150))
imageView.center = self.view.center

2 个答案:

答案 0 :(得分:0)

您可以尝试

var centerCon:NSLayoutConstraint!

let imageView = UIImageView(frame:.zero)

view.addSubview(imageView)

imageView.translatesAutoresizingMaskIntoConstraints = false

centerCon = imageView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)

centerCon.isActive = true

NSLayoutConstraint.activate([

    imageView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),

    imageView.widthAnchor.constraint(equalToConstant: self.view.frame.maxX - 100),

    imageView.heightAnchor.constraint(equalToConstant: self.view.frame.midY - 150)

])

然后更改

centerCon.constant += 200
self.view.layoutIfNeeded()

答案 1 :(得分:0)

如果您使用Storyboard创建视图,则可以为IBOutlet的高度或宽度创建一个UIImageview。例如:

@IBOutlet weak var imageHeightConstraint: NSLayoutConstraint!

然后您可以通过编程方式更改高度:

imageHeightConstraint.constant = 50

并强制视图立即更新其布局:

self.view.layoutIfNeeded()