简体   繁体   English

ios:超视图中的中心视图

[英]ios: Center view in its superview

I'm trying to center my subview with a button in its superview . 我正在尝试使用my subview中的button来集中my subview superview So I want the center of the subview be the center of the superview . 所以我希望subview的中心成为superview subview的中心。 I'm trying that with following code: 我正在尝试使用以下代码:

override func viewDidLoad() {
    self.view.backgroundColor = UIColor.redColor()

    var menuView = UIView()
    var newPlayButton = UIButton()
    //var newPlayImage = UIImage(named: "new_game_button_5cs")
    var newPlayImageView = UIImageView(image: UIImage(named: "new_game_button_5cs"))
    newPlayButton.frame = CGRectMake(0, 0, newPlayImageView.frame.width, newPlayImageView.frame.height)
    newPlayButton.setImage(newPlayImage, forState: .Normal)
    newPlayButton.backgroundColor = UIColor.whiteColor()
    menuView.center = self.view.center
    menuView.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2)
    menuView.backgroundColor = UIColor.whiteColor()*/
    menuView.addSubview(newPlayButton)
}

Unfortunately it doesent seem to work as this is the result: 不幸的是,它似乎工作,因为这是结果:

在此输入图像描述

    UIView *subview = your View To Be Centered In Its SuperView;

    UIView *superView = subview.superview;

    subview.center = [superView convertPoint:superView.center
                                    fromView:superView.superview];

If view is nil(on fromView:), this method instead converts from window base coordinates. 如果view为nil(在fromView :),则此方法将转换为window base coordinates。 Otherwise, both view and the receiver must belong to the same UIWindow object. 否则,视图和接收器都必须属于同一个UIWindow对象。

NOTE: If you use the auto layout stuff, then you have to change the constraints . 注意:如果您使用自动布局的东西,那么您必须更改约束。 not the frame or center. 不是框架或中心。

Good Luck :) 祝好运 :)

Try removing your view width from your superview width, eg: 尝试从超视图宽度中删除视图宽度,例如:

var width: CGFloat = (self.view.bounds.size.width / 2)

// (here goes your view width that you want centralize)

menuView.center = CGPointMake(width, self.view.bounds.size.height / 2)

My working code 我的工作代码

vRate = superview vRate = superview
rcRating = view ( that I want to centralize in vRate ) rcRating = view(我想集中在vRate中)

self.rcRating = AMRatingControl(location: CGPoint(x: 0, y: 0), andMaxRating: 5)
self.vRate.addSubview(self.rcRating)

var width: CGFloat = (self.vRate.bounds.size.width / 2) - self.rcRating.bounds.size.width
self.rcRating.center = CGPointMake(width, self.vRate.bounds.size.height / 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM