2015-06-24 1 views
1

Я использую Xamarin.iOS в Visual Studio 2013 для простого программирования пользовательского интерфейса на C#. Я знаю, что гораздо проще использовать дизайнерский вид, но сейчас он не работает для меня.Как правильно добавить элементы пользовательского интерфейса в представление программно для iOS?

До сих пор мне удалось получить отображение MPMoviePlayerController и TextView, но TextView не будет прокручиваться, хотя я добавил требования для этого.

TextView перекрывает видео, так как я слышу звук, воспроизводимый в фоновом режиме. И UILabel нет, где можно увидеть.

Я подумал о добавлении каждого элемента пользовательского интерфейса в качестве субвизора основного вида, будет отображать элементы в порядке стека, отображающие видео вверху, надписи под текстом и текстом с прокруткой.

В некотором смысле, я хочу, чтобы они сортировали друг друга по слоям. Что я не делаю правильно или что-то не хватает?

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); 

     } 
    } 
} 
+1

Попробуйте установить рамки для всех компонентов пользовательского интерфейса так же, как вы делали с игроком, если кадр не определен результат собирается быть непредсказуемыми. – jrisberg

ответ

1

Im предполагаю, что Вы хотите, это так:

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); 

     } 
    } 
} 

В основном вы были почти там, когда вы устанавливаете рамки для представления с CGRect ИТС new CGRect(x-coord, y-coord, width, height). Поскольку все взгляды были равны 0,0, они находились друг над другом. Также UITextView не будет прокручиваться, поскольку вы сделали его высоту в три раза больше высоты экрана. Если вы хотите, чтобы он прокручивал содержимое (текст), нужно пропустить рамку.

iOS9 представил UIStackView Смотрите видео с WWDC 2015: https://developer.apple.com/videos/wwdc/2015/?id=218 но если вы поддерживаете iOS7/8 есть несколько реализаций сторонних. Xamarin.Forms имеет stacklayout, так что может быть и вариант.

усовершенствованное решение было бы не установить рамки ваших представлений и достаточно использовать ограничение Автокомпоновки так:

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) 
      }); 

     } 
    } 
} 

Это затем позволяет вашему взгляду адаптироваться к размеру экрана, например, макет на iphone4,5,6,6 + iPad должным образом. и ваш UITextView будет прокручиваться, если он слишком большой.

Хороший учебник по Автокомпоновке here

+0

Спасибо, что разобрались! Однако на экране ничего не отображается (просто белый пустой экран). Я озадачен. – TheAmazingKnight

+1

Thats weird, вы можете попробовать удалить часть «partial» в объявлении класса, а затем удалить файлы xib и файл designer.cs, поскольку вам это не нужно, поскольку вы программно настраиваете представление. Если это не поможет, вы сможете отредактировать свой вопрос с тем, где вы добавляете представление? –

+1

Еще раз спасибо за вашу щедрую помощь. Сейчас все работает так, как ожидалось. – TheAmazingKnight

Смежные вопросы