如何使用cgrect在父级视图内垂直居中?
我试图这样做,但是,当我尝试在模拟器中的其他iPhone模型上运行时,图像的位置会发生变化。我需要用cgrect进行准确做到这一点。提前致谢!
func configure() {
//MARK: Logo Image
view.addSubview(logo)
logo.image = UIImage(named: "cafelogo")
logo.layer.cornerRadius = 25
logo.frame = CGRect(x: 100, y: 200, width: 150, height: 150)
I tried to do this one but, the place of the Image changes when I try to run on a different iPhone model in Simulator. I need to do this exactly with CGRect. Thanks in Advance!
func configure() {
//MARK: Logo Image
view.addSubview(logo)
logo.image = UIImage(named: "cafelogo")
logo.layer.cornerRadius = 25
logo.frame = CGRect(x: 100, y: 200, width: 150, height: 150)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用自动限制约束 - 但首先,要向您展示如何使用显式rect /框架来完成此操作:
但是...您必须从
viewDidlayOutsUbviews()< / code>>。否则,
View
的框架尚未放置:请注意,如果
view
更改的框架 - 例如设备旋转 - 您的徽标图像视图将不再以中心为中心。您可以添加一些新代码以重新中心,但是让自动延迟完成所有工作要容易得多。您可以在
viewDidload()
中使用此代码:现在,您的徽标图像视图为150x150,并且始终以
view
为中心。You should be using auto-layout constraints -- but first, to show you how to do this with explicit rect / framing:
but... you have to call this from
viewDidLayoutSubviews()
. Otherwise,view
's frame has not yet been laid-out:Note that if the frame of
view
changes - such as on device rotation - your logo image view will no longer be centered. You could add some new code to re-center it, but it is much easier to let auto-layout do all the work.You can use this code in
viewDidLoad()
:Now your logo image view is 150x150 and will always remain centered in
view
.