gpt4 book ai didi

ios - 添加到父 View Controller 时如何修复 subview 未显示在 subview Controller 中的问题

转载 作者:行者123 更新时间:2023-11-29 05:47:03 27 4
gpt4 key购买 nike

我试图在 swift ios 应用程序中将 subview Controller 添加到父 View Controller ,但是当我添加 subview Controller 时,activityIndi​​catorView 不会出现。我可能会错过什么?以下是可以在 Playground 中尝试的代码片段:

import PlaygroundSupport
import Alamofire

class LoadingViewController: UIViewController {

private lazy var activityIndicator = UIActivityIndicatorView(style: .gray)

override func viewDidLoad() {
super.viewDidLoad()

view.backgroundColor = .white
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(activityIndicator)

NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

// We use a 0.5 second delay to not show an activity indicator
// in case our data loads very quickly.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.0) { [weak self] in
self?.activityIndicator.startAnimating()
}
}

}

// methods for adding and removing child view controllers.
extension UIViewController {
func add(_ child: UIViewController, frame: CGRect? = nil) {
addChild(child)

if let frame = frame {
child.view.frame = frame
}

view.addSubview(child.view)
child.didMove(toParent: self)
}

func remove() {
// Just to be safe, we check that this view controller
// is actually added to a parent before removing it.
guard parent != nil else {
return
}

willMove(toParent: nil)
view.removeFromSuperview()
removeFromParent()
}
}

class MyViewController : UITabBarController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white

let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black

view.addSubview(label)
self.view = view
}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

let loadingViewController = LoadingViewController()
add(loadingViewController, frame: view.frame)
AF.request("http://www.youtube.com").response { response in
print(String(describing: response.response))
loadingViewController.remove()
}
}

}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

loadingViewController View 填充了父 View ,我尝试在不同的点更改背景颜色并且有效。但我尝试添加的 ActivityIndi​​cator 或任何其他 subview 没有出现。

最佳答案

尝试添加该行

activityIndicator.startAnimating()

在 LoadingViewController 类的 viewDidLoad() 方法中

关于ios - 添加到父 View Controller 时如何修复 subview 未显示在 subview Controller 中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56041773/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com