gpt4 book ai didi

ios - 函数无法正确执行(Swift 3)

转载 作者:行者123 更新时间:2023-11-30 12:32:01 25 4
gpt4 key购买 nike

我还是 iOS 开发新手。我的想法是我想将 banner (数据模型)中的 images 值放入其中。所以我需要调用 func getAllBanner 来获取所有值。然后只调用functurnToPage

问题是letcontroller =controllers[index]

fatal error: Index out of range

当我调试时,我注意到惰性变量 Controller :[UIViewController]。这是为什么?

非常感谢任何帮助。

var images: [UIImage]?

var banner: [Banner]?

// Variable that not create onDidLoad
lazy var controllers: [UIViewController] = {

let storyboard = UIStoryboard(name: "Main", bundle: nil)
var controllers = [UIViewController]()

if let images = self.images {
for image in images {
let sliderImageVC = storyboard.instantiateViewController(withIdentifier: Storyboard.sliderImageViewController)

controllers.append(sliderImageVC)
}
}
self.pageViewControllerDelegate?.setupPageController(numberOfPages: controllers.count)

return controllers
}()

override func viewDidLoad() {
super.viewDidLoad()

automaticallyAdjustsScrollViewInsets = false
dataSource = self
delegate = self

self.getAllBanner(strAppID: "1", locationid: "2")
self.turnToPage(index: 0)
}


// To allow to turn page
func turnToPage(index: Int) {
let controller = controllers[index]
var direction = UIPageViewControllerNavigationDirection.forward

if let currentVC = viewControllers?.first {
let currentIndex = controllers.index(of: currentVC)

if currentIndex! > index {
direction = .reverse
}
}

self.configureViewDisplaying(viewController: controller)

setViewControllers([controller], direction: direction, animated: true, completion: nil)
}


// Get Banner
func getAllBanner(strAppID: String, locationid: String) {
Banner.getBanner(strAppID: strAppID, locationID: locationid) { [weak self] banner in
guard let `self` = self else {
return
}
self.banner = banner

// Update UI here
if let banners = self.banner {
for banner in banners {
let endPoint = URL(string: banner.ImageURL)
do {
let data = try Data(contentsOf: endPoint!)
self.images = [UIImage(data: data)!]
} catch {
print("Error")
}
}
}
}
}

最佳答案

您可以使用此代码片段。

func getAllBanner(strAppID: String, locationid: String) {
Banner.getBanner(strAppID: strAppID, locationID: locationid) { [weak self] banner in
guard let `self` = self else {
return
}

self.banner = banner

// Update UI here
if let banners = self.banner {
var images: [UIImage] = []
for banner in banners {
let endPoint = URL(string: banner.ImageURL)
do {
let data = try Data(contentsOf: endPoint!)
images.append(UIImage(data: data)!)
} catch {
print("Error")
}
}
self.images = images
// call turnpage method here
}
}
}

关于ios - 函数无法正确执行(Swift 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43409148/

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