gpt4 book ai didi

ios - 在 UIView 中居中 UIImageView

转载 作者:可可西里 更新时间:2023-11-01 00:55:57 24 4
gpt4 key购买 nike

所以我有一个名为 currentEventImageUIImageView,它位于 UIView blurryBackGround 中。我目前想要将 UIImageView 置于 UIView 的中心。下面是我当前的代码

//Subviews will be added here
view.addSubview(blurryBackGround)
view.addSubview(currentEventImage)
view.addSubview(currentEventDate)

//Constraints will be added here
_ = blurryBackGround.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 17, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: self.view.frame.width, height: 330)
currentEventImage.heightAnchor.constraint(equalToConstant: 330).isActive = true
currentEventImage.topAnchor.constraint(equalTo: blurryBackGround.topAnchor, constant: 5).isActive = true
currentEventImage.center = blurryBackGround.center
blurryBackGround.addSubview(currentEventImage)

知道我该怎么做吗?

currentEventImage.center = blurryBackGround.convert(blurryBackGround.center, from: blurryBackGround.superview)

试过了,还是不行

最佳答案

您可能想尝试以下基于 centerXAnchorcenterYAnchor 的解决方案(随意删除对宽度/高度的限制):

import UIKit

class ViewController: UIViewController {
@IBOutlet var niceIcon:UIImageView!

override func viewDidLoad() {
super.viewDidLoad()

niceIcon.translatesAutoresizingMaskIntoConstraints = false
niceIcon.heightAnchor.constraint(equalToConstant: 100).isActive = true
niceIcon.widthAnchor.constraint(equalToConstant: 100).isActive = true
niceIcon.centerXAnchor.constraint(lessThanOrEqualTo: niceIcon.superview!.centerXAnchor).isActive = true
niceIcon.centerYAnchor.constraint(lessThanOrEqualTo: niceIcon.superview!.centerYAnchor).isActive = true
}
}
  1. Storyboard示例,原始图标放错位置且没有任何限制。

enter image description here

  1. 在模拟器上:

enter image description here


另一种解决方案(有点冗长)可能是在 leftAnchorrightAnchorbottomAnchor 上添加具有相同常量的约束, topAnchor。这个常量代表父 View 和 subview 本身之间的距离。

关于ios - 在 UIView 中居中 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48436115/

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