我正在开发一个应用程序,用户可以用手指拖动视图并更改其中心点。
但是,如果我使用自动布局创建该拖动视图,则会遇到问题。
目前,我正在以编程方式应用其高度宽度和中心约束。
但是无法将中心约束更新为视图中的特定点。
这就是我如何对其SuperView应用中心约束。
// Set center constraints
labelControl.CenterXAnchor.ConstraintEqualTo(this.CenterXAnchor).Active = true;
labelControl.CenterYAnchor.ConstraintEqualTo(this.CenterYAnchor).Active = true;
// On Pangesture
this.AddGestureRecognizer(new UIPanGestureRecognizer((recognizer) =>
{
CGPoint translation = recognizer.TranslationInView(recognizer.View.Superview);
CGPoint newCenter = new CGPoint(lastLocation.X + translation.X, lastLocation.Y + translation.Y);
//this.Center = newCenter; // This does not work as we have applied constraints.
CenterXConstraint.Constant = newCenter.X;
CenterYConstraint.Constant = newCenter.Y;
}));
最佳答案
尝试
NSLayoutConstraint[] list = this.Constraints;
foreach(NSLayoutConstraint c in list)
{
if(c.FirstAttribute == NSLayoutAttribute.CenterX)
{
XConstraint.Constant = newCenter.X;
}
if (c.FirstAttribute == NSLayoutAttribute.CenterY)
{
YConstraint.Constant = newCenter.Y;
}
}