【发布时间】:2016-07-17 17:43:41
【问题描述】:
我在水平的UIStackView 中有两个UIButtons。我想添加一个UIView 作为子视图,这样当我按下其中一个按钮时,视图会水平移动到所选按钮。
我有这个代码:
let selectionView = UIView(frame: CGRect(x: 0, y: 0, width: 70, height: 19))
selectionView.backgroundColor = UIColor.greenColor()
self.incomeButton.addSubview(selectionView) // left button
// left button touched
@IBAction func incomeDidTouch(sender: AnyObject) {
self.incomeButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
self.expensiveButton.setTitleColor(UIColor.grayColor(), forState: .Normal)
UIView.animateWithDuration(0.3) {
self.selectionView.backgroundColor = UIColor.greenColor()
self.selectionView.center = self.incomeButton.center
}
}
// right button touched
@IBAction func expensiveDidTouch(sender: AnyObject) {
self.expensiveButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
self.incomeButton.setTitleColor(UIColor.grayColor(), forState: .Normal)
UIView.animateWithDuration(0.3) {
self.selectionView.backgroundColor = UIColor.redColor()
self.selectionView.center = self.expensiveButton.center
}
当视图添加到左侧按钮时,此代码实际上可以工作。单击按钮时,视图将从左向右和从右向左移动。
但如果我从选择右键开始:
let selectionView = UIView(frame: CGRect(x: 0, y: 0, width: 70, height: 19))
selectionView.backgroundColor = UIColor.redColor()
self.expensiveButton.addSubview(selectionView) // right button
视图只改变颜色,但不会从右向左移动。
这是为什么呢?如何修复我的代码以便视图可以移动?
UPDATE:
我尝试在 UIView 中添加堆栈视图,并在其中添加 selectionView。这是一张快照:
当我在选择右键运行应用程序时仍然遇到问题,selectionView 出现在 containerView 之外(它应该出现在 Expensive 文本的右侧):
当我检查应该选择哪个按钮时,这是viewDidLoad 中的代码:
if type == .Income {
self.selectionView.backgroundColor = UIColor(hex: "28BB9D")
self.selectionView.center = self.incomeButton.center
} else {
self.selectionView.backgroundColor = UIColor(hex: "E5344A")
}
UPDATE 2:
selectionView 的当前约束:
【问题讨论】: