我正在尝试根据我正在显示的应用程序的哪个部分更改UIImageView。
在我的视图控制器中,这可用于设置图像:
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
let imageName = "sectionOneBackground"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
view.addSubview(imageView)
但是,如果我将图像包装成if if:
var imageName = ""
if (section == "one") {
imageName = "sectionOneBackground"
}
if (section == "two") {
imageName = "sectionTwoBackground"
}
if (section == "three") {
imageName = "sectionThreeBackground"
}
然后它就不会出现在视图上。我完全错过了什么。有没有更简单的方法来更改视图的背景?
提前致谢。
答案 0 :(得分:1)
将Imageview创建为全局
的字符串名称class ViewController: UIViewController
{
var imageView : UIImageView!
var imageName : String!
}
在viewdidload上创建imageview就像
一样 override func viewDidLoad() {
super.viewDidLoad()
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
imageName = "sectionOneBackground"
imageView = UIImageView(image: UIImage(named: imageName)!)
imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
view.addSubview(imageView)
}
<强>最后强>
每当您将imageview名称更改为
时if (section == "one") {
imageName = "sectionOneBackground"
}
else if (section == "two") {
imageName = "sectionTwoBackground"
}
else if (section == "three") {
imageName = "sectionThreeBackground"
}
imageView.image = UIImage(named: imageName)
将最终图片名称设置为图片视图
imageView.image = UIImage(named: imageName)