2015-01-02 3 views
0

다음과 같이 사용자에게 우승 한 게임의 수를 보여주기 위해 작성된 하위보기가 있습니다. User profile screen 녹색보기의 너비는 슈퍼 뷰의 너비에 게임 분수 (이 경우 .5)를 곱한 값과 녹색보기의 너비 제한을 계산 된 값으로 변경합니다. iOS의 너비가 올바르게 계산되지 않음

let percent = Float(won)/Float(self.partiesPlayed) //percent of games won, should be .5 
let width = CGFloat(percent) * self.winLoseView.bounds.size.width //multiply width of superview by percent 

self.greenWidthConstraint.constant = CGFloat(width) //change constraint's constant 
UIView.animateWithDuration(2, animations: { // animate change 
    self.view.layoutIfNeeded() 
}) 

enter image description here

문제는 너비가 수퍼의 정확히 절반으로 표시되지 않는 예에서, 예를 들어, 정확하게 올바른 것으로 표시되지 않는다는 것이다.

+0

당신이 자동 레이아웃을 사용하고 있습니까? –

+0

예. 뷰의 너비를 변경하는 대신 너비 제약 조건을 변경하고 제약 조건을 다시로드합니다. – milesper

+0

설명에 따르면 ("정확하지 않습니다.") ... 바쁜 질문 : NSLog 및/또는 디버거를 통해 데이터 문제 (녹색 너비가 잘못 설정 됨)인지 또는 제약/레이아웃 문제 (값이 올바르게 설정되었지만 결과 레이아웃 시스템이 예상 한 것과 다릅니다)? –

답변

1

또 다른 접근법은 다음과 같습니다. greenWidthConstraint을 제거한 다음 빨간색보기의 너비와 동일한 제한 조건으로 다시 적용하고 승수를 백분율로 설정하지 않는 이유는 무엇입니까? 그렇게하면 회전 또는 다른 크기 변경을 지원하면 고정 너비 값 상수에 대해 걱정할 필요가 없습니다. 아직/신속한 w 파까지 아니지만, 여기가 목표 - C에있다 : 여기

[self.view removeConstraint:self.constraint]; 
self.constraint = [NSLayoutConstraint constraintWithItem:self.greenView 
               attribute:NSLayoutAttributeWidth 
               relatedBy:NSLayoutRelationEqual 
                toItem:self.redView 
               attribute:NSLayoutAttributeWidth 
               multiplier:PERCENTAGE 
               constant:0]; 
[self.view addConstraint:self.constraint]; 

// Animate the layoutIfNeeded.... 

스위프트 버전 것

: (@milesper에서 제공가)

let percent = Float(won)/Float(self.partiesPlayed) 
var constraint = NSLayoutConstraint(item: self.greenSection, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.winLoseView, attribute: NSLayoutAttribute.Width, multiplier: CGFloat(percent), constant: 0.0 as CGFloat) 
self.view.addConstraint(constraint) 
UIView.animateWithDuration(2, animations: { 
    self.view.layoutIfNeeded() 
}) 
+0

완벽하게 작동했습니다! 나는 이것을 단지 Swift로 번역하려고한다. – milesper

관련 문제