UIView中的UIImageView中心

时间:2018-01-25 05:18:30

标签: ios swift uiview

所以我的UIImageView名为currentEventImage,位于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)

试过这个并且没有用

2 个答案:

答案 0 :(得分:3)

您可能希望尝试基于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. 故事板示例,原始图标放错地方,没有任何限制。
  2. enter image description here

    1. 在模拟器上:
    2. enter image description here

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

答案 1 :(得分:0)

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

这里我给出了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)