You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在iPad的Swift Playground Book中如何将视图居中于ViewController?

让Swift Playground Book中的视图居中的方法

当然可以让newView在父视图里居中啦!给你两种实用的方法,你可以根据自己的习惯选择:

方法1:通过计算Frame实现(适配现有写法)

你之前的代码里硬写了x:0, y:0,这会让视图左上角对齐。想要居中的话,我们可以根据父视图的实际尺寸来计算newView的位置,这样不管设备是iPad还是其他尺寸,都能准确居中:

override public func loadView() {
    let view = UIView()
    view.backgroundColor = .white
    self.view = view // 这里不用硬设frame,系统会自动适配Playground的视图尺寸
    
    let newViewSize = CGSize(width: 375, height: 375)
    // 计算居中的frame:父视图宽度减去子视图宽度的一半就是x坐标,y同理
    let newViewFrame = CGRect(
        x: (view.bounds.width - newViewSize.width) / 2,
        y: (view.bounds.height - newViewSize.height) / 2,
        width: newViewSize.width,
        height: newViewSize.height
    )
    
    let newView = UIView(frame: newViewFrame)
    newView.backgroundColor = .lightBlue // 加个背景色方便你看到效果
    view.addSubview(newView)
}

方法2:使用Auto Layout(更推荐,自适应各种尺寸)

这是苹果官方推荐的布局方式,能更好适配不同设备的屏幕尺寸(包括iPad的各种型号),而且不用手动计算坐标:

override public func loadView() {
    let view = UIView()
    view.backgroundColor = .white
    self.view = view
    
    let newView = UIView()
    newView.backgroundColor = .lightBlue
    // 必须设置这个属性,关闭自动转换的约束,让我们自己的Auto Layout生效
    newView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(newView)
    
    // 激活约束:让newView在父视图中水平、垂直居中,同时固定宽高
    NSLayoutConstraint.activate([
        newView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        newView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        newView.widthAnchor.constraint(equalToConstant: 375),
        newView.heightAnchor.constraint(equalToConstant: 375)
    ])
}

小提示:尽量不要给父视图硬设frame,Playground的视图尺寸会根据运行设备自动调整,直接用self.view = view就好,父视图的bounds会自动匹配实际显示的大小~

内容的提问来源于stack exchange,提问作者Charles-olivier Demers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:09:02