StackView 中的 AvPlayer

AvPlayer inside a StackView

我有一个垂直 StackView,按顺序包含一个 UILabel 和一组 UIButton(这要归功于水平 StackView。 我需要使用 AVPlayer 在 UILabel 和 UIButtons 之间插入视频作为第二个元素。

你能建议我最好的方法吗?我正在尝试使用通用 UIView 并将框架和子层传递给它,但它不起作用。 我正在使用 Xamarin iOS/tvOS(所以在 C# 中),但我可以阅读 Swift

中的示例

谢谢

更新

最后的问题是错误地使用了 uiview 框架。

我通过 iOS 设计师设置了我的布局结构,不是按照建议的编程方式,但感谢@land 用户提供这些代码行:

contentView.Layer.AddSublayer(playerLayer);
//update its frame immediately
contentView.LayoutIfNeeded();
playerLayer.Frame = contentView.Bounds;

刘易斯

您可以尝试创建一个 UIView 来显示 AVPlayerLayer 并设置它的位置来布局您的 AVPlayer。我们可以将此 contentView 放在 ViewController 视图中的 StackView 中或 StackView 外部。

我建议把这个view直接放到ViewController的View里面,这样我们就可以用autolayout来布局了。

首先,我创建了一个 UIView,其顶部约束等于垂直 StackView 的底部约束,底部约束等于水平 StackView 的顶部约束,例如:

UIView contentView = new UIView();
contentView.TranslatesAutoresizingMaskIntoConstraints = false;
View.AddSubview(contentView);

NSLayoutConstraint topConstraint = NSLayoutConstraint.Create(contentView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, VerticalStackView, NSLayoutAttribute.Bottom, 1, 0);
NSLayoutConstraint leadConstraint = NSLayoutConstraint.Create(contentView, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, View, NSLayoutAttribute.Leading, 1, 0);
NSLayoutConstraint trailConstraint = NSLayoutConstraint.Create(contentView, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, View, NSLayoutAttribute.Trailing, 1, 0);
NSLayoutConstraint heightConstraint = NSLayoutConstraint.Create(contentView, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 0, 100);
NSLayoutConstraint bottomConstraint = NSLayoutConstraint.Create(contentView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, HorizontalStackView, NSLayoutAttribute.Top, 1, 0);

View.AddConstraints(new NSLayoutConstraint[] { topConstraint, leadConstraint, trailConstraint, bottomConstraint });
contentView.AddConstraint(heightConstraint);

然后你可以将你的 AVPlayerLayer 放在这个视图中并让它的框架等于这个视图:

AVPlayerItem playerItem = new AVPlayerItem(new NSUrl(NSBundle.MainBundle.PathForResource("test.mp4", null), false));
aVPlayer = new AVPlayer(playerItem);
AVPlayerLayer playerLayer = AVPlayerLayer.FromPlayer(aVPlayer);

contentView.Layer.AddSublayer(playerLayer);
//update its frame immediately
contentView.LayoutIfNeeded();
playerLayer.Frame = contentView.Bounds;

如果您确实想在 StackView 中实现这一点。只需将 contentView 放入 StackView 并设置其高度限制以显示 AVPlayer。