![](/img/trans.png)
[英]Swift unwraps value as nil when in closure but successfully unwraps elsewhere in code?
[英]Set UIButton Image in Swift - currently unwraps as nil
我很難設置UIButton的圖像。 我已經檢查過如何做到這一點的其他帖子,它看起來很簡單(但是,我在這里)。
在我的程序中,按鈕顯示的圖像取決於trip.weather。 我在嘗試設置按鈕的圖像之前使用開關來設置圖像。 但是,在調試時,控制台顯示以下內容:
'2015-05-03 13:40:31.117 PackPlanner [581:4465] <UIImage:0x7fd2a843fac0>,{600,300}致命錯誤:在展開可選值(lldb)時意外發現nil'
class TripOverviewViewController: UITableViewController {
@IBOutlet var highTempLabel: UILabel!
@IBOutlet var lowTempLabel: UILabel!
@IBOutlet var weatherLabel: UILabel!
@IBOutlet var locationLabel: UILabel!
@IBOutlet var dateLabel: UILabel!
@IBOutlet var numOfPeopleLabel: UILabel!
@IBOutlet var sunriseLabel: UILabel!
@IBOutlet var sunsetLabel: UILabel!
@IBOutlet weak var weatherButtonImage: UIButton!
@IBAction func weatherButton(sender: UIButton) {
}
var tripItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the trip detail.
if let trip: Trip = self.tripItem as? Trip{
if var label = self.locationLabel {
label.text = trip.location
}
if var label = self.numOfPeopleLabel {
label.text = trip.numOfPeople.stringValue
}
if var label = self.dateLabel {
var formattedDate = NSDateFormatter.localizedStringFromDate(trip.startDate, dateStyle: .LongStyle, timeStyle: .NoStyle)
label.text = formattedDate
}
if var label = self.weatherLabel {
label.text = trip.weather
}
var theImage = UIImage(named: "Sunny") as UIImage!
switch trip.weather {
case "Partly Cloudy":
theImage = UIImage(named:"PartlyCloudy")
case "Light Snow":
theImage = UIImage(named:"LightSnow")
case "Rainy":
theImage = UIImage(named:"Rainy")
default:
theImage = UIImage(named:"Sunny")
}
NSLog(" \(theImage.description)") //for debugging
self.weatherButtonImage.setImage(theImage, forState: .Normal)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.configureView()
}
你確定圖像存在並且不是零嗎? UIImage可能無法找到名為“Sunny”的圖像。 另一種可能性是self.weatherButtonImage在那時是零(我看它是一個出口),所以在viewDidLayoutSubviews完成IB布局時嘗試設置它。
在NSLog之后嘗試這個(“(theImage.description)”)
if let tempButton = self.weatherButtonImage
{
tempButton.setImage(theImage, forState:.Normal)
} else
{ NSLog("Button is nil")
}
確定你的按鈕是否為零。
如果您的按鈕為零,請在故事板中重新連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.