У меня есть таблица с 4 ячейками (эскизы для отображения из URI). Если URI пуст, я хочу отобразить изображение заполнителя. Если не пусто, я хочу отображать индикатор активности во время загрузки.Ошибка инициализации переменных
То, что я очень «быстрый и грязный» код - но это работает:
func setCell(previewView1: String, previewView2: String, previewView3: String, previewView4: String, id: String) {
self.loadPreview1(previewView1)
self.loadPreview2(previewView2)
self.loadPreview3(previewView3)
self.loadPreview4(previewView4)
self.cellID = id;
}
func loadPreview1(urlString: String) {
if urlString == "" {
self.previewView1.image = UIImage(named: "imagePlatzhalter")
self.activityIndicator1.stopAnimating(); // Animation stoppen
}
else {
self.activityIndicator1.startAnimating() // Animation Start
var imgURL = NSURL(string: urlString);
let request: NSURLRequest = NSURLRequest(URL: imgURL!);
let mainQueue = NSOperationQueue.mainQueue();
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
// Convert the downloaded data in to a UIImage object
let image = UIImage(data: data)
// Update the cell
self.activityIndicator1.stopAnimating(); // Animation stoppen
self.previewView1.image = image;
}
else {
println("Error: \(error.localizedDescription)")
self.previewView1.image = UIImage(named: "imagePlatzhalter")
self.activityIndicator1.stopAnimating(); // Animation stoppen
}
})
}
}
func loadPreview2(urlString: String) {
if urlString == "" {
self.previewView2.image = UIImage(named: "imagePlatzhalter")
self.activityIndicator2.stopAnimating(); // Animation stoppen
}
else {
self.activityIndicator2.startAnimating() // Animation Start
var imgURL = NSURL(string: urlString);
let request: NSURLRequest = NSURLRequest(URL: imgURL!);
let mainQueue = NSOperationQueue.mainQueue();
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
// Convert the downloaded data in to a UIImage object
let image = UIImage(data: data)
// Update the cell
self.activityIndicator2.stopAnimating(); // Animation stoppen
self.previewView2.image = image;
}
else {
println("Error: \(error.localizedDescription)")
self.previewView2.image = UIImage(named: "imagePlatzhalter")
self.activityIndicator2.stopAnimating(); // Animation stoppen
}
})
}
}
func loadPreview3(urlString: String) {
: same as 1 and 2 with references on self.previewView3 and self.activityIndicator3...
}
func loadPreview4(urlString: String) {
: same as 1 and 2 with references on self.previewView4 and self.activityIndicator4...
}
Это решение работает хорошо, но я хочу, чтобы реорганизовать теперь код в более удобном решении. Это мой подход:
func previewImage (urlString: String, controlIndex: Int) {
var previewViewImage : UIImage;
var activityIndicator : UIActivityIndicatorView;
if controlIndex == 1 {
previewViewImage = self.previewView1.image!;
activityIndicator = self.activityIndicator1;
} else if controlIndex == 2 {
previewViewImage = self.previewView2.image!;
activityIndicator = self.activityIndicator2;
} else if controlIndex == 3 {
previewViewImage = self.previewView3.image!;
activityIndicator = self.activityIndicator3;
} else if controlIndex == 4 {
previewViewImage = self.previewView4.image!;
activityIndicator = self.activityIndicator4;
}
if urlString == "" {
// Set image to placeholder image:
previewViewImage = UIImage(named: "imagePlatzhalter")!;
}
else {
activityIndicator.startAnimating() // Animation Start
var imgURL = NSURL(string: urlString);
// Check ob Image gecacht ist/TODO
let request: NSURLRequest = NSURLRequest(URL: imgURL!);
let mainQueue = NSOperationQueue.mainQueue();
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
// Convert the downloaded data in to a UIImage object
let image = UIImage(data: data)
// Store the image in to our cache
//self.imageCache[urlString] = image
// Update the cell
previewViewImage = image!;
}
else {
println("Error: \(error.localizedDescription)")
previewViewImage = UIImage(named: "imagePlatzhalter")!;
}
})
}
// Stop activity indicator:
activityIndicator.stopAnimating();
}
Но Xcode бросает здесь 3 ошибки:
activityIndicator.startAnimating()
Error: "Variable activityIndicator used before initialized
же на
activityIndicator.stopAnimating();
И в обратный вызов я получил ошибку:
"Variable previewViewImage captured by a closure before being initialized"
Я новичок в Swift и не понимаю, почему мой код не будет работать. Может ли кто-нибудь помочь мне реорганизовать код выше?
Черт спасибо огромное. Изменено последнее, если, если работает, как шарм. Не знаю до сих пор, что Xcode/Swift настолько строг ... –
Swift просто делает вам одолжение. Это устраняет возможность поиска ошибок, настаивая на том, что вы правильно инициализировали свои переменные. – vacawama
Это стиль Swift, чтобы оставить точки с запятой на концах линий. – vacawama