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

iOS Swift中如何将子视图居中添加至另一子视图?Lottie视图居中失败求助

解决Lottie动画视图无法在父视图中居中的问题

嘿,我懂你现在的困扰——把Lottie动画加到viewOn里却没法居中对吧?你直接设置frame.size和center的方式踩了两个常见坑:一是布局时机不对(视图的frame在viewDidLoad阶段往往还没经过AutoLayout计算,值不准确),二是直接修改frame属性不如用AutoLayout适配性强。

给你两种靠谱的解决方案:

方案一:使用AutoLayout约束(推荐)

AutoLayout会自动处理视图的位置、尺寸变化,适配不同屏幕,是iOS布局的最佳实践。代码这么写:

@IBOutlet weak var viewOn: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    
    let animationView = LOTAnimationView(name: "restless_gift_ii")
    animationView.loopAnimation = true
    animationView.contentMode = .scaleToFill
    animationView.animationSpeed = 1
    animationView.backgroundColor = .black
    
    // 关键:关闭自动转换约束,否则AutoLayout不会生效
    animationView.translatesAutoresizingMaskIntoConstraints = false
    viewOn.addSubview(animationView)
    
    // 添加居中+匹配父视图尺寸的约束
    NSLayoutConstraint.activate([
        animationView.centerXAnchor.constraint(equalTo: viewOn.centerXAnchor),
        animationView.centerYAnchor.constraint(equalTo: viewOn.centerYAnchor),
        animationView.widthAnchor.constraint(equalTo: viewOn.widthAnchor),
        animationView.heightAnchor.constraint(equalTo: viewOn.heightAnchor)
    ])
    
    animationView.play()
}

方案二:在布局完成后设置Frame

如果你更习惯用frame布局,一定要在viewDidLayoutSubviews方法里操作——这个方法会在视图的布局完全确定后调用,此时viewOn的frame才是准确的:

@IBOutlet weak var viewOn: UIView!
var animationView: LOTAnimationView!

override func viewDidLoad() {
    super.viewDidLoad()
    
    animationView = LOTAnimationView(name: "restless_gift_ii")
    animationView.loopAnimation = true
    animationView.contentMode = .scaleToFill
    animationView.animationSpeed = 1
    animationView.backgroundColor = .black
    
    viewOn.addSubview(animationView)
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    
    // 此时viewOn的布局已确定,直接让动画视图填满父视图
    animationView.frame = viewOn.bounds
    // 也可以分开写:
    // animationView.frame.size = viewOn.bounds.size
    // animationView.center = viewOn.center
}

补充下:你的原代码失效,核心原因是在viewDidLoad里viewOn的frame还没经过AutoLayout的最终计算,尺寸和位置都是临时值,这时候设置动画视图的frame自然会错位。另外用viewOn.bounds比frame更合适,因为bounds是视图自身的坐标系(原点在左上角,尺寸是视图实际大小),直接赋值就能让动画视图填满父视图并自动居中。

内容的提问来源于stack exchange,提问作者amirtmgr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:24:36