以编程方式使用 AutoLayout 和 UIScrollView [英] Using AutoLayout and UIScrollView programmatically
问题描述
我正在尝试从这里复制这个问题的答案:Xamarin iOS:滚动视图中的自动布局?但不使用界面构建器.代码很简单,我有 _scrollView
背景色为绿色.然后我有 _contentView
背景颜色为红色.我将 _contentView
添加到 _scrollView
并将 _scrollView
添加到 ViewController
中的 View.当我运行它时,我得到的只是绿色控制器,红色控制器从未出现在里面.
I am trying to make a copy of the answer from this question here: Xamarin iOS: Auto Layout within scroll view? but without using the interface builder. The code is simple, I have _scrollView
which has background color green. Then I have _contentView
which has background color red. I add _contentView
to _scrollView
and I add _scrollView
to View in the ViewController
. When I run this, all I get is Green controller, the red one never appears inside of it.
public async override void ViewDidLoad()
{
base.ViewDidLoad();
//ui
View.BackgroundColor = UIColor.White;
//views
_scrollView = new UIScrollView();
_scrollView.BackgroundColor = UIColor.Green;
_scrollView.TranslatesAutoresizingMaskIntoConstraints = false;
_contentView = new UIView();
_contentView.TranslatesAutoresizingMaskIntoConstraints = false;
_contentView.BackgroundColor = UIColor.Red;
var label = new UILabel();
label.TranslatesAutoresizingMaskIntoConstraints = false;
label.Text = "Text";
_contentView.AddSubview(label);
_scrollView.AddSubview(_contentView);
View.AddSubviews(new UIView[] { _scrollView });
_scrollView.TopAnchor.ConstraintEqualTo(View.TopAnchor, 100).Active = true;
_scrollView.LeftAnchor.ConstraintEqualTo(View.LeftAnchor, 20).Active = true;
_scrollView.RightAnchor.ConstraintEqualTo(View.RightAnchor, -20).Active = true;
_scrollView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor, -100).Active = true;
_contentView.TopAnchor.ConstraintEqualTo(_contentView.Superview.TopAnchor).Active = true;
_contentView.RightAnchor.ConstraintEqualTo(_contentView.Superview.RightAnchor).Active = true;
_contentView.LeftAnchor.ConstraintEqualTo(_contentView.Superview.LeftAnchor).Active = true;
_contentView.BottomAnchor.ConstraintEqualTo(_contentView.Superview.BottomAnchor).Active = true;
_contentView.WidthAnchor.ConstraintEqualTo(_contentView.Superview.WidthAnchor).Active = true;
label.TopAnchor.ConstraintEqualTo(label.Superview.TopAnchor, 100).Active = true;
label.BottomAnchor.ConstraintEqualTo(label.Superview.BottomAnchor, 100).Active = true;
label.LeftAnchor.ConstraintEqualTo(label.Superview.LeftAnchor, 100).Active = true;
label.RightAnchor.ConstraintEqualTo(label.Superview.RightAnchor, 100).Active = true;
}
推荐答案
我能够使它工作的唯一方法是将 BottomAnchor 添加到 ContentView 中的最后一个 UIView.我创建了一个带有演示代码的 GitHub 存储库 here
The only way I was able to make it work was by adding BottomAnchor to the last UIView inside ContentView. I created a GitHub repo with demo code here
这篇关于以编程方式使用 AutoLayout 和 UIScrollView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!