Center align Labels and images inside UIView programatically with Swift

南楼画角 提交于 2019-12-03 21:39:56

Firstly, change .AlignAllCenterX to .AlignAllCenterY, the reason is that"H:|-[label]-5-[brainView]-|" specifies how views position horizontally, you want label and brainView to have the same center Y position.

Secondly, make a subview that contains all 3 views, then center this subview inside the black rectangle. You can use costView as the subview. Below is some modified code based on your existing code.

costView!.addSubview(label)

//Constraints
var viewsDict = Dictionary <String, UIView>()
viewsDict["label"] = label
viewsDict["brainView"] = costBrainImageView
viewsDict["costLabel"] = costLabel

costView!.addConstraints(
    NSLayoutConstraint.constraintsWithVisualFormat(
        "V:|[label]|", options: nil, metrics: nil, views: viewsDict))
costView!.addConstraints(
    NSLayoutConstraint.constraintsWithVisualFormat(
        "V:|[brainView]|", options: nil, metrics: nil, views: viewsDict))
costView!.addConstraints(
    NSLayoutConstraint.constraintsWithVisualFormat(
        "V:|[costLabel]|", options: nil, metrics: nil, views: viewsDict))
costView!.addConstraints(
    NSLayoutConstraint.constraintsWithVisualFormat(
        "H:|-[label]-5-[brainView]-5-[costLabel]-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: viewsDict))
costView!.backgroundColor = UIColor.redColor()

// center costView inside self
let centerXCons = NSLayoutConstraint(item: costView!, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0);
let centerYCons = NSLayoutConstraint(item: costView!, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0);
self.addConstraints([centerXCons, centerYCons])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!