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

Swift 4中Facebook登录按钮意外覆盖Activity Indicator问题

解决Activity Indicator被Facebook登录按钮覆盖的问题

嘿,我一眼就发现你代码里的核心错误了,先给你指出来:

在addActivityIndicator方法里,你写了这行完全搞反逻辑的代码:

activityIndicator.bringSubview(toFront: self.view)

bringSubview(toFront:)是父视图的方法,作用是把某个子视图拉到自己的子视图层级最前面。你应该让self.view来调用这个方法,把activityIndicator作为参数传进去,正确写法是:

self.view.bringSubview(toFront: activityIndicator)

除此之外,还有几个优化点能彻底解决这个问题,顺便让你的代码更健壮:

1. 调整子视图的添加顺序

UIKit的子视图层级规则是:后添加的视图会显示在更早添加的视图上面。你现在先加了Activity Indicator,再添加Facebook登录按钮,所以登录按钮自然会覆盖Indicator。要么把setupFBloginButton()的调用放在addActivityIndicator()前面,要么在添加完登录按钮后,再把Indicator拉到最前面。

2. 给Activity Indicator改用AutoLayout布局

你现在用frame来设置Indicator的位置,但在viewDidLoad阶段,视图的最终尺寸还没确定(比如不同设备、横竖屏切换),这可能导致Indicator位置偏移。换成AutoLayout会更稳妥:

func addActivityIndicator(_ activityIndicator: UIActivityIndicatorView) {
    activityIndicator.backgroundColor = UIColor(red:0.10, green:0.10, blue:0.10, alpha:0.5)
    activityIndicator.layer.cornerRadius = 8
    activityIndicator.translatesAutoresizingMaskIntoConstraints = false // 关闭自动约束转换
    self.view.addSubview(activityIndicator)
    
    // 用约束固定大小和居中位置
    NSLayoutConstraint.activate([
        activityIndicator.widthAnchor.constraint(equalToConstant: 70),
        activityIndicator.heightAnchor.constraint(equalToConstant: 70),
        activityIndicator.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
        activityIndicator.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
    ])
    
    // 确保Indicator在最顶层
    self.view.bringSubview(toFront: activityIndicator)
}

3. 显示Indicator时再确认层级

还有个稳妥的小技巧:在你要显示Activity Indicator的时机(比如用户点击登录按钮后),再调用一次层级调整的代码,避免后续添加的其他视图意外覆盖它。比如在登录回调里:

func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
    activityIndicator.startAnimating()
    // 再次确保Indicator在最前面
    self.view.bringSubview(toFront: activityIndicator)
    // 执行后续登录逻辑...
}

把这些修改结合起来,应该就能完美解决登录按钮覆盖Activity Indicator的问题了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:58:52