以编程方式将帧 CGReact x 位置设置为中间位置,如中心XAnchor NSLayoutConstraint



我正在创建一个简单的应用程序,该应用程序通过使用图像frame计算将图像设置为圆形。

这是我声明图像变量:

lazy var imageUserDetailProfileView: UIImageView = {
let imageView = UIImageView()

imageView.contentMode = .scaleAspectFill
imageView.layer.borderWidth = 1
imageView.image = UIImage(named: "profile-icon")
imageView.layer.borderColor = UIColor(red:0.00, green:0.50, blue:0.00, alpha:1.0).cgColor
imageView.clipsToBounds = true
return imageView

}()

这是我使图像的框架宽度和高度变成圆形

imageUserDetailProfileView.frame = CGRect(x: view.frame.midX, y: 20,width: 100, height: 100)
imageUserDetailProfileView.layer.cornerRadius = imageUserDetailProfileView.frame.height/2

现在我希望图像应该留在屏幕中间,就像使用具有方法centerXAnchorNSLayoutConstraint一样。

如何解决这个问题?

let midX = view.frame.size.width / 2
let midY = view.frame.size.height / 2

试试这段代码。 在任何视图的中心设置图像的自定义方法。只需调用方法并传递图像和视图。根据用途定制。斯威夫特 4

func setImageInCenterOfView(image:UIImage,view:UIView) {
let imageWidth:CGFloat = 100
let myImageView = UIImageView.init(frame: CGRect.init(x: (view.frame.size.width/2)-imageWidth/2, y: (view.frame.size.height/2)-imageWidth/2, width: imageWidth, height: imageWidth))
myImageView.clipsToBounds = true
myImageView.layer.cornerRadius = myImageView.frame.size.height/2
myImageView.image = image
view.addSubview(myImageView)
view.layoutIfNeeded()
}

最新更新