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

使用navigationController.pushViewController时,根视图控制器为何随目标视图被推入?

问题原因与解决方案

核心问题是FlagViewController错误继承了ViewController——你的根视图控制器ViewController包含完整的列表UI(tableView及相关逻辑),当FlagViewController继承它时,会自动加载父类的所有属性和viewDidLoad中的setupUI流程,导致push后的详情页同时存在父类的tableView和自身的flagView,看起来就像根控制器的副本在背景层,还能被交互点击。

解决步骤

  1. 修改FlagViewController的继承关系,让它直接继承UIViewController,而非ViewController
  2. 调整详情页的UI配置,确保独立显示

修正后的FlagViewController代码

import UIKit

class FlagViewController: UIViewController {
    let flagView: UIImageView = {
        let flagView = UIImageView()
        flagView.contentMode = .scaleAspectFit // 优化图片显示比例
        return flagView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white // 避免透显底层视图
        setupUI()
    }
    
    private func setupUI() {
        self.view.addSubview(flagView)
        flagView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            flagView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100),
            flagView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -100),
            flagView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20),
            flagView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20),
            flagView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            flagView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
        ])
    }
}

额外优化说明

  • 移除错误继承后,详情页不会再加载根控制器的tableView,彻底解决背景交互问题
  • 添加背景色和图片内容模式,提升详情页的UI展示效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 17:30:53