我正在尝试以编程方式将视频限制在页面中心。我的AV控制器名为avPlayerController
。
我已经给出了x和y值以及宽度和高度:
avPlayerController.view.frame = CGRect(x: 36 , y: 20, width: 343, height: 264)
那么我该如何居中呢?
我已经尝试过了:Programmatically Add CenterX/CenterY Constraints
但是,你可以猜测它不起作用:(
这是我的代码:
super.viewDidLoad()
let filepath: String? = Bundle.main.path(forResource: "rockline", ofType: "mp4")
let fileURL = URL.init(fileURLWithPath: filepath!)
avPlayer = AVPlayer(url: fileURL)
let avPlayerController = AVPlayerViewController()
avPlayerController.player = avPlayer
avPlayerController.view.frame = CGRect(x: 36 , y: 20, width: 343, height: 264)
// hide/show control
avPlayerController.showsPlaybackControls = false
// play video
avPlayerController.player?.play()
self.view.addSubview(avPlayerController.view)
avPlayerController.view.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
答案 0 :(得分:1)
你可以试试这个。
avPlayerController.view.enableAutoLayoutConstraint()
avPlayerController.view.setCenterXConstraint(.equal, constantValue: 0)
avPlayerController.view.setCenterYConstraint(.equal, constantValue: 0)
extension UIView
{
//Method to making translatesAutoresizingMaskIntoConstraints false.
func enableAutoLayoutConstraint()
{
self.translatesAutoresizingMaskIntoConstraints = false
}
//Method to set Center-X Consttraint
func setCenterXConstraint(_ relationType:NSLayoutRelation , constantValue:CGFloat)->NSLayoutConstraint
{
let constraint = NSLayoutConstraint(item: self, attribute:.centerX, relatedBy: relationType, toItem: self.superview, attribute: .centerX, multiplier: 1, constant: constantValue)
self.superview?.addConstraint(constraint)
return constraint
}
//Method to set Center-Y Consttraint
func setCenterYConstraint(_ relationType:NSLayoutRelation , constantValue:CGFloat)->NSLayoutConstraint
{
let constraint = NSLayoutConstraint(item: self, attribute:.centerY, relatedBy: relationType, toItem: self.superview, attribute: .centerY, multiplier: 1, constant: constantValue)
self.superview?.addConstraint(constraint)
return constraint
}
}
答案 1 :(得分:1)
这里是代码,并附有说明。
CGRect.zero
,它会在必要时进行最佳通信。viewDidLoad
中设置约束,只应创建一次。false
。当您在代码中学习自动布局时,这是最常见的错误。这是一个以宽度343和高度264为中心的视图(任何视图)的示例:
let myView = UIView() // note, I'm not setting any frame
override func viewDidLoad() {
super.viewDidLoad()
view.translatesAutoresizingMaskIntoConstraints = false
myView.translatesAutoresizingMaskIntoConstraints = false
myView.widthAnchor.constraint(equalToConstant: 343.0).isActive = true
myView.heightAnchor.constraint(equalToConstant: 264.0).isActive = true
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
这就是它的全部!但....
我建议再做一件事。不要在设置高度和宽度时使用常量。这不是"自适应"。您的4英寸iPhone SE的屏幕尺寸为568x320,这可能看起来居中且足够大。但在屏幕尺寸为736x414的iPhone Plus上,它可能非常小。 (更不用说12.9英寸iPad Pro了!)
注意我的代码如何使用 superview 作为centerX / centerY锚点。 (而不是equalToConstant
它equalTo
。)对宽度和高度做同样的事情。通过使用multiplier
和constant
以及UILayoutGuide
,您可以使您的布局适应Apple向您投射的任何屏幕尺寸。