gpt4 book ai didi

ios - 如何使用swift以编程方式添加具有某些约束的 ImageView ?

转载 作者:行者123 更新时间:2023-11-28 05:43:05 24 4
gpt4 key购买 nike

我是 iOS 开发新手。如果使用 Storyboard,我可以像这样在 View Controller 中放置一个 ImageView

enter image description here

我需要以编程方式制作类似的东西。

所以我有来自名为 RevealingSplashView 的库的自定义 View ,但我需要向该自定义 UI View 添加一个 ImageView 。我只知道添加 ImageView ,也许是这样的

let imageName = "yourImage.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
revealingSplashView.addSubview(imageView)

但我不知道如何将 ImageView 的约束设置为

一个。对齐中心 x 到 super View

与 super View 成比例的宽度 0.8

高度限制 = 25

将底部与安全区域对齐 = 32

怎么做?

这是我想添加 ImageView 之前使用的代码

let screenSize = UIScreen.main.bounds
let iconWidth = (screenSize.width) * 0.8
let iconHeight = iconWidth * 1 // ratio 1:1
revealingSplashView = RevealingSplashView(iconImage: UIImage(named: "Loading Page Asset")!,iconInitialSize: CGSize(width: iconWidth, height: iconHeight), backgroundColor: AppColor.mainYellow.getUIColor())
revealingSplashView.animationType = SplashAnimationType.twitter
revealingSplashView.imageView?.contentMode = .scaleAspectFill


// add loading indicator to RevealingSplashView Programatically
revealingSplashViewIndicator.color = UIColor.white
revealingSplashViewIndicator.frame = CGRect(x: 0.0, y: 0.0, width: 30.0, height: 30.0)
revealingSplashViewIndicator.center = CGPoint(x: self.view.center.x, y: self.view.center.y + (iconHeight/2) + 64 )
revealingSplashView.addSubview(revealingSplashViewIndicator)
revealingSplashViewIndicator.bringSubviewToFront(self.revealingSplashView)
revealingSplashViewIndicator.startAnimating()

let window = UIApplication.shared.keyWindow
window?.addSubview(revealingSplashView)

最佳答案

我推荐使用 anchor :

let imageName = "yourImage.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
revealingSplashView.addSubview(imageView)

// you need to turn off autoresizing masks (storyboards do this automatically)
imageView.translatesAutoresizingMaskIntoConstraints = false

// setup constraints, it is recommended to activate them through `NSLayoutConstraint.activate`
// instead of `constraint.isActive = true` because of performance reasons
NSLayoutConstraint.activate([
imageView.centerXAnchor.constraint(equalTo: revealingSplashView.centerXAnchor),
imageView.widthAnchor.constraint(equalTo: revealingSplashView.widthAnchor, multiplier: 0.8),
imageView.heightAnchor.constraint(equalToConstant: 25),
imageView.bottomAnchor.constraint(equalTo: revealingSplashView.safeAreaLayoutGuide.bottomAnchor, constant: -32),
])

关于ios - 如何使用swift以编程方式添加具有某些约束的 ImageView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55916477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com