UIView.animateWithDuration 在 UITableviewCell 中不起作用
UIView.animateWithDuration does not work within a UITableviewCell
我有一个 UITableviewCell
subclass,其中包含一个 UIButton
,它被放置在屏幕外(右侧),并带有自动布局水平 Space 对其超级视图的约束-312。
现在我想在选择单元格时将此约束设置为值 -8 的动画。
我在单元格 class 中为此约束创建了一个出口,并尝试使用以下代码为该约束设置动画:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier("VariationsTableViewCell", forIndexPath: indexPath) as! VariationsCell
UIView.animateWithDuration(1.0, delay: 0.0, options: .CurveEaseOut, animations: {
cell.buttonRightSideConstraint.constant = -8
}, completion: { finished in
println("Button revealed!")
})
}
不幸的是,这不起作用。如果我使用 .reloadData()
重新加载 tableview,则会显示按钮,这告诉我自动布局约束已更新但动画不会被触发。
使用自动布局设置动画时,必须使用 layoutIfNeeded
设置约束变化的动画。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("VariationsTableViewCell", forIndexPath: indexPath) as! VariationsCell
UIView.animateWithDuration(1.0, delay: 0.0, options: .CurveEaseOut) {
cell.layoutIfNeeded()
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier("VariationsTableViewCell", forIndexPath: indexPath) as! VariationsCell
cell.buttonRightSideConstraint.constant = -8
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
}
我有一个 UITableviewCell
subclass,其中包含一个 UIButton
,它被放置在屏幕外(右侧),并带有自动布局水平 Space 对其超级视图的约束-312。
现在我想在选择单元格时将此约束设置为值 -8 的动画。
我在单元格 class 中为此约束创建了一个出口,并尝试使用以下代码为该约束设置动画:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier("VariationsTableViewCell", forIndexPath: indexPath) as! VariationsCell
UIView.animateWithDuration(1.0, delay: 0.0, options: .CurveEaseOut, animations: {
cell.buttonRightSideConstraint.constant = -8
}, completion: { finished in
println("Button revealed!")
})
}
不幸的是,这不起作用。如果我使用 .reloadData()
重新加载 tableview,则会显示按钮,这告诉我自动布局约束已更新但动画不会被触发。
使用自动布局设置动画时,必须使用 layoutIfNeeded
设置约束变化的动画。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("VariationsTableViewCell", forIndexPath: indexPath) as! VariationsCell
UIView.animateWithDuration(1.0, delay: 0.0, options: .CurveEaseOut) {
cell.layoutIfNeeded()
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier("VariationsTableViewCell", forIndexPath: indexPath) as! VariationsCell
cell.buttonRightSideConstraint.constant = -8
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
}