evgenyneu/center-vfl
소개
Centering a view in a super view with Visual Format Language using Auto Layout in iOS/Swift
웹 및 앱 개발측정된 스타 증가
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- 기록 수집 중
서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.
README.md
OriginalCentering a view in a super view with visual format language using Auto Layout in iOS/Swift
This is an example of centeing a label in its view using Visual Format Language. Tested in iOS 7, 8 and 9.
Here is the code from view controller that does the trick:
// Center horizontally
var constraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:[superview]-(<=1)-[label]",
options: NSLayoutFormatOptions.AlignAllCenterX,
metrics: nil,
views: ["superview":view, "label":label])
view.addConstraints(constraints)
// Center vertically
constraints = NSLayoutConstraint.constraintsWithVisualFormat(
"H:[superview]-(<=1)-[label]",
options: NSLayoutFormatOptions.AlignAllCenterY,
metrics: nil,
views: ["superview":view, "label":label])
view.addConstraints(constraints)

How it works
This code is something like theory of special relativity. I can not say I completely understand it. But it seems to work.
We use two visual format strings:
@"V:[superview]-(<=1)-[label]"withAlignAllCenterXoption@"H:[superview]-(<=1)-[label]"withAlignAllCenterYoption
It aligns X and Y centres of the label and its superview. The (<=1) inequality constraints are needed to allow those centering constraints do their job. If we had just [superview][label] it would probably stick the edges of the label and its superview together.
Feedback is welcome
If you need help or want to improve this technique feel free to create a pull request, or comment on this stackoverflow answer.
관련 프로젝트 살펴보기
불러오는 중…