所以我的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)
试过这个并且没有用
答案 0 :(得分:3)
您可能希望尝试基于centerXAnchor
和centerYAnchor
的以下解决方案(随意删除宽度/高度限制):
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 :(得分: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)