问题描述
我试图在Xcode 6.1中以编程方式设置UIImageView:
I'm trying to set UIImageView programmatically in Xcode 6.1:
@IBOutlet weak var bgImage: UIImageView!
var image : UIImage = UIImage(named:"afternoon")!
bgImage = UIImageView(image: image)
bgImage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(bgImage)
但是Xcode用bgImage = UIImageView(image: image)
图片"afternoon"
表示预期声明"是PNG,我的理解是PNG不需要在XCode 6.1中进行扩展.
But Xcode is saying "expected declaration" with bgImage = UIImageView(image: image)
Image "afternoon"
is a PNG, and my understanding is PNG does not need an extension in XCode 6.1.
也尝试过bgImage.image = UIImage(named: "afternoon")
,但仍然得到:
Also tried just bgImage.image = UIImage(named: "afternoon")
, but still get:
更新
好吧,我已经将更新UIImageView
的代码放入了viewDidLoad
函数中,但是UIImageView
仍然没有显示图像(该图像以下午.png的形式存在于基本目录中):
OK, I have put the code to update UIImageView
into the viewDidLoad
function, but UIImageView
is still not showing the image (which exists in the base directory as afternoon.png):
@IBOutlet weak var bgImage: UIImageView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
updateTime()
var timer = NSTimer()
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
var image : UIImage = UIImage(named:"afternoon")!
bgImage = UIImageView(image: image)
}
推荐答案
由于已将bgImage分配并链接为IBOutlet,因此无需将其初始化为UIImageView ...而是设置了所有要做的事情. image属性,如bgImage.image = UIImage(named: "afternoon")
.运行此代码后,由于已经使用插座分配了图像,因此图像看起来很好.
Since you have your bgImage assigned and linked as an IBOutlet, there is no need to initialize it as a UIImageView... instead all you need to do is set the image property like bgImage.image = UIImage(named: "afternoon")
. After running this code, the image appeared fine since it was already assigned using the outlet.
但是,如果它不是插座,并且您尚未将其连接到情节提要/xib文件上的UIImageView对象,则可以执行以下操作...
However, if it wasn't an outlet and you didn't have it already connected to a UIImageView object on a storyboard/xib file, then you could so something like the following...
class ViewController: UIViewController {
var bgImage: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
var image: UIImage = UIImage(named: "afternoon")!
bgImage = UIImageView(image: image)
bgImage!.frame = CGRectMake(0,0,100,200)
self.view.addSubview(bgImage!)
}
}
这篇关于使用Xcode 6.1/Swift以编程方式将图像设置为UIImageView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!