我想要在 Storyboard中完成的任务相当简单,但我无法仅通过代码来实现它 - 这对于我的特定问题来说是必要的。
我的代码:
scrollView.TopAnchor.ConstraintEqualTo(this.View.TopAnchor, 50).Active = true;
scrollView.BottomAnchor.ConstraintEqualTo(this.View.BottomAnchor, 50).Active = true;
scrollView.LeftAnchor.ConstraintEqualTo(this.View.LeftAnchor, 50).Active = true;
scrollView.RightAnchor.ConstraintEqualTo(this.View.RightAnchor, 50).Active = true;
scrollView.BackgroundColor = UIColor.Black;
View.AddSubview(scrollView);
我想做的事情:
最后,我想将自己定位在类似于 Storyboard 中的顶部+底部布局指南的位置 - 代码没有反射(reflect)这一点。我使用了 this.Top(/Bottom)LayoutGuide,它基本上产生了相同的错误。
我为什么要这样做?
我的布局需要适应方向的变化——约束似乎是解决问题的方法。使用布局指南似乎也以某种方式在 Storyboard 中起作用-因此它也必须在代码中可行吗?同样,现在导航 + 标签栏都覆盖了滚动条。
我收到此错误消息:
(这可能会帮助那些因为类似问题从谷歌来到这里的人)
Foundation.MonoTouchException: Objective-C exception thrown. Name: NSGenericException Reason: Unable to activate
constraint with anchors <NSLayoutYAxisAnchor:0x174274080 "UIScrollView:0x102245400.top"> and
<NSLayoutYAxisAnchor:0x1702707c0 "UIView:0x10135e760.top"> because they have no common ancestor.
Does the constraint or its anchors reference items in different view hierarchies? That's illegal. ...
如果有人愿意将我推向正确的方向,我将不胜感激。我似乎还找不到传递给约束的正确 anchor 。
最佳答案
您必须先添加 subview 。然后你可以添加约束。还需要将 TranslatesAutoresizingMaskIntoConstraints 设置为 false。
scrollView.translatesAutoresizingMaskIntoConstraints = false;
View.AddSubview(scrollView);
scrollView.TopAnchor.ConstraintEqualTo(this.View.TopAnchor, 50).Active = true;
scrollView.BottomAnchor.ConstraintEqualTo(this.View.BottomAnchor, 50).Active = true;
scrollView.LeftAnchor.ConstraintEqualTo(this.View.LeftAnchor, 50).Active = true;
scrollView.RightAnchor.ConstraintEqualTo(this.View.RightAnchor, 50).Active = true;
关于ios - 如何使用编程约束对齐我的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39853616/