简体   繁体   English

如何为iOS以编程方式正确地将UI元素添加到视图中?

[英]How do I properly add UI elements into a view programmatically for iOS?

I am using Xamarin.iOS in Visual Studio 2013 to build a simple user interface programmatically in C#. 我在Visual Studio 2013中使用Xamarin.iOS在C#中以编程方式构建简单的用户界面。 I know it's much easier to use the designer view, but it's not working for me right now. 我知道使用设计器视图要容易得多,但现在对我而言不起作用。

So far, I have managed to get the MPMoviePlayerController and the TextView showing, but the TextView won't scroll, even though I added requirements to do so. 到目前为止,我设法显示了MPMoviePlayerController和TextView,但是即使我添加了要求,TextView也不会滚动。

The TextView overlaps the video as I can hear audio playing in the background. TextView与视频重叠,因为我可以在后台听到音频播放。 And the UILabel is no where to be seen. UILabel是无处可见的地方。

I thought adding each UI element as a subView of the main View, will show the elements in a stack order displaying the video at the top, label right under the video and textview with scroll. 我以为将每个UI元素添加为主视图的子视图,将以堆栈顺序显示这些元素,从而在顶部显示视频,在视频下方标记标签,并滚动显示textview。

In a way, I want them to sort of stack each other layer by layer. 从某种意义上说,我希望他们彼此之间逐层堆叠。 What am I not doing right or am missing something? 我做错了什么或缺少什么?

using System;
using System.Drawing;

using Foundation;
using UIKit;
using MediaPlayer;

public partial class VideoViewController : UIViewController
    {
        MPMoviePlayerController moviePlayer;
        UILabel label;
        UITextView textView;
        public VideoViewController() : base("VideoViewController", null)
        {
        }

        public override void DidReceiveMemoryWarning()
        {
            // Releases the view if it doesn't have a superview.
            base.DidReceiveMemoryWarning();

            // Release any cached data, images, etc that aren't in use.
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Perform any additional setup after loading the view, typically from a nib.
            moviePlayer = new MPMoviePlayerController(NSUrl.FromString("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")); // Use FromString() to play video directly from web.
            moviePlayer.View.Frame = new CoreGraphics.CGRect(0, 20, this.View.Frame.Size.Width, 180); // size of the video frame
            moviePlayer.ScalingMode = MPMovieScalingMode.AspectFit; // show the video relative to the video size dimensions
            moviePlayer.PrepareToPlay();
            moviePlayer.Play();
            this.View.AddSubview(moviePlayer.View); // add the view after video starts playing to display it

            // UILabel
            label = new UILabel();
            label.Text = "Tutorial";
            label.Font.WithSize(36);
            this.View.AddSubview(label.ViewForBaselineLayout);

            // UITextView
            textView = new UITextView();
            textView.Editable = false;
            textView.ScrollEnabled = true;
            textView.UserInteractionEnabled = true;
            textView.ViewForBaselineLayout.Frame = new CoreGraphics.CGRect(0, 0, this.View.Frame.Size.Width, this.View.Frame.Size.Height*3);
            textView.Text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. [shorten text for this post] "; // shorten text for this post
            this.View.AddSubview(textView);

        }
    }
}

Im guessing you want it like this: 我想你想要这样:

using System;
using System.Drawing;

using Foundation;
using UIKit;
using MediaPlayer;
using CoreGraphics;

namespace CHANGE_THIS_TO_YOUR_NAME_SPACE
{
    public partial class VideoViewController : UIViewController
    {
        MPMoviePlayerController moviePlayer;
        UILabel label;
        UITextView textView;

        public VideoViewController () : base ("VideoViewController", null)
        {
        }

        public override void DidReceiveMemoryWarning ()
        {
            // Releases the view if it doesn't have a superview.
            base.DidReceiveMemoryWarning ();

            // Release any cached data, images, etc that aren't in use.
        }

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            // Perform any additional setup after loading the view, typically from a nib.
            moviePlayer = new MPMoviePlayerController (NSUrl.FromString ("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")); // Use FromString() to play video directly from web.
            moviePlayer.View.Frame = new CGRect (0, 20, View.Frame.Size.Width, 180); // size of the video frame
            moviePlayer.ScalingMode = MPMovieScalingMode.AspectFit; // show the video relative to the video size dimensions
            moviePlayer.PrepareToPlay ();
            moviePlayer.Play ();
            View.Add (moviePlayer.View); // add the view after video starts playing to display it

            // UILabel
            label = new UILabel (new CGRect(0,200, View.Frame.Size.Width, 50));
            label.Text = "Tutorial";
            label.Font.WithSize (36);
            View.Add (label.ViewForBaselineLayout);

            // UITextView
            textView = new UITextView ();
            textView.Editable = false;
            textView.ScrollEnabled = true;
            textView.UserInteractionEnabled = true;
            textView.ViewForBaselineLayout.Frame = new CGRect (0, 250, View.Frame.Size.Width, View.Frame.Size.Height * 3);
            textView.Text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. [shorten text for this post] "; // shorten text for this post
            View.Add (textView);

        }
    }
}

Basically you were almost there, when you are setting the frame for the view with a CGRect its new CGRect(x-coord, y-coord, width, height) . 基本上,当您使用CGRect为其new CGRect(x-coord, y-coord, width, height)设置视图框架时,您几乎到了。 As all of the views were 0,0 they were place on top of each other. 由于所有视图均为0,0,因此它们彼此重叠。 Also the UITextView wont scroll as you have made its height three times the height of the screen. 而且, UITextView不会滚动,因为您将其高度设置为屏幕高度的三倍。 If you want it to scroll the content(text) needs to extend past the frame. 如果要滚动,内容(文本)需要扩展到框架之外。

iOS9 introduced UIStackView See this video from WWDC 2015: https://developer.apple.com/videos/wwdc/2015/?id=218 but if you are supporting iOS7/8 there are some third party implementations. iOS9引入了UIStackView观看WWDC 2015的以下视频: https : //developer.apple.com/videos/wwdc/2015/? id=218,但是如果您支持iOS7 / 8,则可以使用某些第三方实现。 Xamarin.Forms has a stacklayout so that might be an option too. Xamarin.Forms具有堆栈布局,因此也可以选择。

An improved solution would be to not set the frame of your views and rather use auto layout constraints like so: 一种改进的解决方案是不设置视图框架,而是使用自动布局约束,如下所示:

using System;
using System.Drawing;

using Foundation;
using UIKit;
using MediaPlayer;
using CoreGraphics;

namespace CHANGE_THIS_TO_YOUR_NAME_SPACE
{
    public partial class VideoViewController : UIViewController
    {
        MPMoviePlayerController moviePlayer;
        UILabel label;
        UITextView textView;

        public VideoViewController () : base ("VideoViewController", null)
        {
        }

        public override void DidReceiveMemoryWarning ()
        {
            // Releases the view if it doesn't have a superview.
            base.DidReceiveMemoryWarning ();

            // Release any cached data, images, etc that aren't in use.
        }

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            // Perform any additional setup after loading the view, typically from a nib.
            moviePlayer = new MPMoviePlayerController (NSUrl.FromString ("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")); // Use FromString() to play video directly from web.
            moviePlayer.View.TranslatesAutoresizingMaskIntoConstraints = false;
//          moviePlayer.View.Frame = new CGRect (0, 20, View.Frame.Size.Width, 180); // size of the video frame
            moviePlayer.ScalingMode = MPMovieScalingMode.AspectFit; // show the video relative to the video size dimensions
            moviePlayer.PrepareToPlay ();
            moviePlayer.Play ();
            View.Add (moviePlayer.View); // add the view after video starts playing to display it

            // UILabel
//          label = new UILabel (new CGRect(0,200, View.Frame.Size.Width, 50));
            label = new UILabel ();
            label.TranslatesAutoresizingMaskIntoConstraints = false;
            label.Text = "Tutorial";
            label.Font.WithSize (36);
            View.Add (label.ViewForBaselineLayout);

            // UITextView
            textView = new UITextView ();
            textView.TranslatesAutoresizingMaskIntoConstraints = false;
            textView.Editable = false;
            textView.ScrollEnabled = true;
            textView.UserInteractionEnabled = true;
//          textView.ViewForBaselineLayout.Frame = new CGRect (0, 250, View.Frame.Size.Width, View.Frame.Size.Height * 3);
            textView.Text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. [shorten text for this post] "; // shorten text for this post
            View.Add (textView);

            SetUpAutoLayoutConstraints ();
        }

        private void SetUpAutoLayoutConstraints()
        {
            View.AddConstraints (new [] {
                NSLayoutConstraint.Create(moviePlayer.View, NSLayoutAttribute.Width, NSLayoutRelation.Equal, View, NSLayoutAttribute.Width, 1, 0),
                NSLayoutConstraint.Create(moviePlayer.View, NSLayoutAttribute.Height, NSLayoutRelation.Equal, View, NSLayoutAttribute.Width, 0.5625f, 0), // setting it to this to keep your aspect ratio
                NSLayoutConstraint.Create(moviePlayer.View, NSLayoutAttribute.Top, NSLayoutRelation.Equal, View, NSLayoutAttribute.Top, 1, 20),
                NSLayoutConstraint.Create(moviePlayer.View, NSLayoutAttribute.Left, NSLayoutRelation.Equal, View, NSLayoutAttribute.Left, 1, 0)
            });

            View.AddConstraints (new [] {
                NSLayoutConstraint.Create(label, NSLayoutAttribute.Width, NSLayoutRelation.Equal, View, NSLayoutAttribute.Width, 1, 0),
                NSLayoutConstraint.Create(label, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1, 50),
                NSLayoutConstraint.Create(label, NSLayoutAttribute.Top, NSLayoutRelation.Equal, moviePlayer.View, NSLayoutAttribute.Bottom, 1, 0),
                NSLayoutConstraint.Create(label, NSLayoutAttribute.Left, NSLayoutRelation.Equal, View, NSLayoutAttribute.Left, 1, 0)
            });

            View.AddConstraints (new [] {
                NSLayoutConstraint.Create(textView, NSLayoutAttribute.Width, NSLayoutRelation.Equal, View, NSLayoutAttribute.Width, 1, 0),
                NSLayoutConstraint.Create(textView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, View, NSLayoutAttribute.Bottom, 1, 0),
                NSLayoutConstraint.Create(textView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, label, NSLayoutAttribute.Bottom, 1, 0),
                NSLayoutConstraint.Create(textView, NSLayoutAttribute.Left, NSLayoutRelation.Equal, View, NSLayoutAttribute.Left, 1, 0)
            });

        }
    }
}

This then lets your view adapt to the screen size, eg layout on iphone4,5,6,6+ iPad properly. 然后,这可以使您的视图适应屏幕尺寸,例如在iphone4、5、6、6 + iPad上的布局正确。 and your UITextView will scroll if its too big. 如果UITextView太大,则会滚动。

A Good tutorial on auto layout here 在汽车设计一个很好的教程在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Silverlight中以编程方式在画布中添加UI元素? - how to add UI elements programmatically in canvas in silverlight? 如何以编程方式设置视图控制器 - How do I set a view controller programmatically 如何以编程方式添加日志记录筛选器? - How do I programmatically add logging filters? 如何在 Xamarin 中动态添加 UI 元素(如“选择器”)到 View? - How to add UI elements (like "picker") to View dynamically in Xamarin? 如何将项目正确添加到ObjectListView? - How do I add the items to the ObjectListView properly? 如何以编程方式将NewLines添加到TFS工作项文本框? - How do I programmatically add NewLines to a TFS work item textbox? 如何以编程方式将事件处理程序添加到.NET按钮? - How Do I Add Event Handlers to .NET Buttons Programmatically? 如何以编程方式将项目引用添加到wix项目? - How do I add project references to a wix project programmatically? 如何以编程方式创建kmltreeview文件夹并在其中添加地标? - How do I programmatically create kmltreeview folders and add placemarks in them? 如何在运行时以编程方式将项目添加到“水平列表”? - How do I programmatically add items to a Horizontal List at runtime?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM