您正在尝试将显式框架/边界设置与自动布局约束混合并匹配。如您所见,这行不通。
当你运行这一行时:
[[recognizer view] setBounds:CGRectMake(100, 100, bounds.size.width, bounds.size.height)];
您正在更改视图的 bounds。这不会改变任何约束。 (实际上,设置bounds 甚至不会更改frame,但这是另一个问题。)
如果您想移动一个视图,并保持该视图与其他元素之间的约束,您需要更新该视图上的 约束,而不是其边界(或框架)。
因此,您希望保留对约束的引用,或在需要时找到它们,并根据需要更新 .constant 值。
以下是通过查找 CenterX 和 CenterY 约束(而不是保存引用)来更改点击视图中心的示例:
- (void)handleGesture:(UIGestureRecognizer*)recognizer
{
// get the view that was tapped
UIView *tappedView = [recognizer view];
// get that view's constraints
NSArray *constraints = [tappedView constraints];
// we want to find the CenterX constraint
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstAttribute = %d", NSLayoutAttributeCenterX];
NSArray *filteredArray = [constraints filteredArrayUsingPredicate:predicate];
// if it doesn't have a CenterX constraint, return
if(filteredArray.count == 0){
return;
}
NSLayoutConstraint *centerX = [filteredArray objectAtIndex:0];
// we want to find the CenterY constraint
predicate = [NSPredicate predicateWithFormat:@"firstAttribute = %d", NSLayoutAttributeCenterY];
filteredArray = [constraints filteredArrayUsingPredicate:predicate];
// if it doesn't have a CenterY constraint, return
if(filteredArray.count == 0){
return;
}
NSLayoutConstraint *centerY = [filteredArray objectAtIndex:0];
// we now have references to the CenterX and CenterY constraints of the tapped view,
// so we can change the .constant values and the related constraints to the other view will be maintained
[UIView animateWithDuration:0.15
animations:^
{
centerX.constant -= 100.0;
centerY.constant -= 100.0;
}
completion:^(BOOL finished)
{
}];
}