그냥 중간 충분하지 않습니다. y 축에서 어디로 가야할지 결정해야합니다.
여기 (뷰의 중앙 즉,) x와 y의 중간에 라벨을 두는 예이다
func placeTheLabelAtCenterOfView(view: UIView, withRect rect: CGRect, andText text: String) {
let label = UILabel(frame: rect)
label.textColor = UIColor.whiteColor()
label.font = UIFont(name: label.font.fontName, size: 50)
label.textAlignment = NSTextAlignment.Center
label.text = text
// Disable automatic translation of constraints
label.setTranslatesAutoresizingMaskIntoConstraints(false)
// Create the needed constraints
let horizontalConstraint = NSLayoutConstraint(
item: label,
attribute: NSLayoutAttribute.CenterX,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.CenterX,
multiplier: 1,
constant: 0
)
let verticalConstraint = NSLayoutConstraint(
item: label,
attribute: NSLayoutAttribute.CenterY,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.CenterY,
multiplier: 1,
constant: 0
)
// Add the subView (before adding the constraints)
view.addSubview(label)
// Add the constraints
view.addConstraints([
horizontalConstraint,
verticalConstraint,
])
}
감사! 완벽하게 작동합니다! – 24GHz
당신은 환영합니다 –