ios - 如何使用编程约束对齐我的控件

标签 ios xamarin.ios nslayoutconstraint

我想要在 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/

相关文章:

ios - 将 SVG 文件与 monotuch 结合使用

ios - 从 View Controller 对负 y 原点进行动画处理会破坏约束

ios - 找不到 Xcode 7.0 Beta 4 的 GameCenter 框架图像错误

ios - 没有 Storyboard 中场景的某些类别的目标

ios - ABAddressBookRequestAccessWithCompletion iOS 7 和信号量

c# - 提示用户在 Xamarin Forms 中启用蓝牙

c# - Xamarin 和 native 库

非 sibling 之间的 iOS Autolayout 约束

ios - 我在理解如何使用自动布局的逻辑时遇到问题

web-services - 使用 JSON 框架将数值发送到 Web 服务