我正在尝试在Xcode 6.1中以编程方式设置UIImageView:
@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) Image的“预期声明” "afternoon"是PNG,我的理解是PNG不需要在XCode 6.1中进行扩展。
bgImage = UIImageView(image: image)
"afternoon"
也尝试过bgImage.image = UIImage(named: "afternoon"),但仍然得到:
bgImage.image = UIImage(named: "afternoon")
更新
好的,我已将要更新的代码UIImageView放入viewDidLoad函数中,但UIImageView仍未显示图像(该图像以下午.png的形式存在于基本目录中):
UIImageView
viewDidLoad
@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")。运行此代码后,由于已使用插座分配了图像,因此图像看起来很好。
但是,如果它不是插座,并且您尚未将其连接到情节提要/ xib文件上的UIImageView对象,则可以执行以下操作…
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!) } }