2016-08-08 4 views
1

UIView (또는 UIStackView) 내에 여러 요소 (레이블 및 단추)를 가운데에 놓으려고합니다. Center Alignment와 Distribution Fill 및 Spacing 10을 사용하여 UIStackView에 요소를 추가하려고 시도했지만 요소가 왼쪽에서 계속 배치됩니다. 나는 변화하는 센터를 시도했다. 아직도 운이 없다. 내가 달성하기 위해 노력하고있어UIView 내부에 여러 요소를 가운데에 맞추는 방법

:

-2 요소 [------- 라벨 버튼 -------].

[--label-button-button--] 세 가지 요소가 있습니다.

스페이서를 사용하지 않고이를 수행 할 수있는 방법이 있습니까? 이론적으로 제약 조건을 사용할 수는 있지만 요소 수가 많아서 좋은 생각인지는 잘 모르겠습니다.

let simpleView = UIView() 
simpleView.addSubview(text) 
simpleView.addSubview(button) 


let leftLeading = NSLayoutConstraint(item: text, attribute: 
    .LeadingMargin, relatedBy: .Equal, toItem: simpleView, 
        attribute: .LeadingMargin, multiplier: 1.0, 
        constant: 10) 

let leftLeading2 = NSLayoutConstraint(item: button, attribute: 
    .LeadingMargin, relatedBy: .Equal, toItem: simpleView, 
        attribute: .LeadingMargin, multiplier: 1.0, 
        constant: 10) 

simpleView.addConstraint(leftLeading) 
simpleView.addConstraint(leftLeading2) 


simpleView.translatesAutoresizingMaskIntoConstraints = false 
simpleView.sizeToFit() 

newView.addSubview(simpleView) 

let horizontalConstraint = NSLayoutConstraint(item: simpleView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: newView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) 
newView.addConstraint(horizontalConstraint) 

let verticalConstraint = NSLayoutConstraint(item: simpleView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: newView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) 
newView.addConstraint(verticalConstraint) 
이 내가 무엇을 얻을 때문에 내가 뭔가 잘못하고 있어야합니다

이 (newView이 버튼은 파란색, 텍스트 레이블이없는 빨간색) :

enter image description here

+0

균등하게 배포하려고 했습니까? – KotaBear233

답변

0

보기를 작성, 센터보기 필요한 곳. 그런 다음 해당 뷰 내부에서 각 요소를 삽입하고 각 요소에 5를 써 넣거나 요소간에 원하는 간격을 지정하는 프로그래밍 방식 NSLayoutConstraint를 제공 할 수 있습니다. 수는 중요하지 않을

VIEW [ELEMENT ELEMENT ELEMENT]

. NSLayoutConstraints를 살펴보고 view.addConstraints를 사용해야합니다.

+0

제발, 내 편집 좀 봐. – HelloimDarius

관련 문제