我有一个带有子视图的视图,旨在向用户显示他们赢得和输掉的游戏的比例,如下所示:
绿色视图的宽度是通过获取超视图的宽度,乘以赢得的游戏的比例(在这种情况下为.5),并将绿色视图的宽度约束更改为计算值来计算的。
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()
})
问题是宽度看起来并不完全正确,例如在这个例子中,它看起来并不是超视图的一半。
答案 0 :(得分:1)
以下是另一种方法:为什么不删除greenWidthConstraint
并使用等于红色视图宽度的约束重新应用它,并将乘数设置为赢得的百分比。这样,如果您支持旋转或任何其他尺寸更改,您不必担心固定宽度值常量。我还没有达到标准的速度,但是在Objective-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....
这里的Swift版本:(由@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()
})