gpt4 book ai didi

ios - 使用 Switch 语句从 Xcassets 加载 imageView

转载 作者:行者123 更新时间:2023-11-29 01:51:56 25 4
gpt4 key购买 nike

我在 Xcassets 中有 @1 @2 和 @3 的图像,并尝试使用下面的代码将图像加载到 ScrollView 页面上,该代码根据图像的年龄来切换图像。由位置决定页面,并在viewWillLoad函数中调用switch语句。图像未加载,但声音正常,所以我知道问题出在图像加载上。你能帮忙吗?

override func viewDidDisappear(animated: Bool) {
self.imageView.removeFromSuperview()
self.imageView.image = nil
}



override func viewWillAppear(animated: Bool) {

showImageView()

let tapGestureImage = UITapGestureRecognizer(target: self, action: Selector("handleTapGestureImage:"))
imageView.addGestureRecognizer(tapGestureImage)
imageView.userInteractionEnabled = true
}




// MARK: BWWalkthroughPage Implementation

func walkthroughDidScroll(position: CGFloat, offset: CGFloat) {

// getting the page number from the scroll position. First page loads as nil so want it to be zero.

screenPage = Int(((position / view.bounds.size.width) + 1) - 1)
}



func showImageView() {

// change imageView in bundle depending on which scrollview page you are.
switch screenPage {

case 0:

self.imageView.image = UIImage(named: "Aligator", inBundle: NSBundle.mainBundle(), compatibleWithTraitCollection: self.traitCollection)
self.view.addSubview(imageView)

case 1:

self.imageView.image = UIImage(named: "Bear", inBundle: NSBundle.mainBundle(), compatibleWithTraitCollection: self.traitCollection)
self.view.addSubview(imageView)

default:
self.imageView.image = nil
}
}

最佳答案

您需要了解一些重要事项。您不需要一遍又一遍地从 View 层次结构中添加/删除 ImageView 。只需调用 imageView.image = nil 就足够了。

第二件事是您不需要使用完整方法 UIImage(named:inBundle:compatibleWithTraitCollection:)。您应该能够简单地使用 UIImage(named:)。如果您发现自己不得不使用前者,那么在您职业生涯的这个阶段,您可能会承受更大的负担。

第三件事是,当你覆盖一个方法时,99% 的情况下你必须调用 super。

这是一个应该有效的例子:

import UIKit

class MyViewController: UIViewController {

override fun viewDidLoad() {
super.viewDidLoad()
let gestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleTapGestureImage:"))
imageView.addGestureRecognizer(gestureRecognizer)
imageView.userInteractionEnabled = true
}

override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated: animated)
self.imageView.image = nil
}

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated: animated)
showImageView()
}

func walkthroughDidScroll(position: CGFloat, offset: CGFloat) {
screenPage = Int(((position / view.bounds.size.width) + 1) - 1)
}

func showImageView() {
switch screenPage {
case 0:
imageView.image = UIImage(named: "Aligator")
case 1:
imageView.image = UIImage(named: "Bear")
default:
imageView.image = nil
}
}
}

关于ios - 使用 Switch 语句从 Xcassets 加载 imageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31306038/

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