【问题标题】:Center UIImageView inside UIView在 UIView 中居中 UIImageView
【发布时间】:2018-01-25 05:18:30
【问题描述】:

所以我有一个名为currentEventImageUIImageView,它位于UIView blurryBackGround 中。我目前想在UIView 中居中UIImageView。以下是我当前的代码

//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)

试过了,还是不行

【问题讨论】:

  • 你检查过这个吗 - stackoverflow.com/a/11253622/4637057
  • 你的意思是 2012 年使用的旧语法和过时的方法@VincentJoy
  • 这不起作用@VincentJoy
  • 请评论包含heightAnchortopAnchor的行并重试

标签: ios swift uiview


【解决方案1】:

您可能想尝试基于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. 故事板示例,原始图标放错位置且没有任何限制。

  1. 在模拟器上:


另一个解决方案(更详细一点)可能是在leftAnchorrightAnchorbottomAnchortopAnchor 上添加具有相同常量的约束。这样的常数代表父视图和子视图本身之间的距离。

【讨论】:

    【解决方案2】:

    您可以使用以下示例代码:-

    这里我将 View 的宽度和高度设为 (200,400),对于 UIImageView 我将大小设为 (50,50)

    let whitView = UIView(frame:CGRect(self.view.frame.size.width/2-200/2,self.view.frame.size.height/2-400/2,200,400))
    whitView.backgroundcolor = UIColor.white
    view.addSubview(whitView)
    let imgView = UIImageView(frame:CGRect(whitView.frame.size.width/2-50/2,whitView.frame.size.height/2-50/2,50,50))
    imgView.image = UIImage(named: "abc.png")
    whitView.addSubview(imgView)
    

    【讨论】:

      猜你喜欢
      • 2015-05-07
      • 1970-01-01
      • 1970-01-01
      • 2015-12-28
      • 2010-11-28
      • 1970-01-01
      • 2011-07-04
      • 2013-09-09
      相关资源
      最近更新 更多