为什么在contentView中心添加UIView总是不在中心?

时间:2016-08-07 05:37:30

标签: ios swift

我想在其contentView中心添加一个UIView。

    @IBOutlet weak var contentView: UIView!
override func viewDidLoad() {
    let view = UIView(frame: CGRectMake(0,0,100,100))
    view.backgroundColor = UIColor.blueColor()
    contentView.backgroundColor = UIColor.redColor()
    contentView.addSubview(view)
    view.center = contentView.center

}

但结果是

enter image description here

我忘记了什么吗?

更新 谢谢@Wain的小费,约束工作。 根据{{​​3}}

    override func viewDidLoad() {
    let view = UIView(frame: CGRectMake(0,0,100,100))
    view.backgroundColor = UIColor.blueColor()
    contentView.backgroundColor = UIColor.redColor()
    view.translatesAutoresizingMaskIntoConstraints = false
    contentView.addSubview(view)
    let widthConstraint = NSLayoutConstraint(item: view, attribute: .Width, relatedBy: .Equal,
                                             toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100)
    let heightConstraint = NSLayoutConstraint(item: view, attribute: .Height, relatedBy: .Equal,
                                              toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100)
     let xConstraint = NSLayoutConstraint(item: view, attribute: .CenterX, relatedBy: .Equal, toItem: contentView, attribute: .CenterX, multiplier: 1, constant: 0)
    let yConstraint = NSLayoutConstraint(item: view, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0)
    NSLayoutConstraint.activateConstraints([heightConstraint,  widthConstraint,xConstraint, yConstraint])
}

我认为我在StoryBoard中使用约束来contentView(centerX,centerY,Equal Width,equal Height to superView)。
在ViewDidLoad中,contentView的帧大小不正确 当我设置view.center = contentView.center时,它不起作用 我需要以编程方式使用约束来设置视图的位置 感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用此代码

@IBOutlet weak var contentView: UIView!

然后将其添加到viewDidLoad

let view = UIView(frame: CGRectMake(0,0,100,100))
let contentView = UIView(frame: self.view.frame)
view.backgroundColor = UIColor.blueColor()
contentView.backgroundColor = UIColor.redColor()
view.center = contentView.center
contentView.addSubview(view)
self.view.addSubview(contentView)

这是结果

enter image description here

答案 1 :(得分:-1)

试试这个 -

//set locale, 
setlocale(LC_ALL,"US");

//set the date to be converted
$date = '2016-08-07';

//convert date to month name
$month_name =  ucfirst(strftime("%B", strtotime($date)));

echo $month_name;