我試圖在UICollectionView中創建一個警報列表,其中「on」警報具有圖像(alarmImg)和時間標籤(alarmLbl),而「關閉」警報具有圖像和空白時間標籤。我希望「關閉」警報圖像居中,而「開啓」警報圖像有一個偏移量來解釋標籤。Swift:出現神祕約束條件
這是我的代碼cellForItemAtIndexPath
,其中cell是出隊單元,alarmLbls是警報時間的字符串數組。
cell.alarmLbl.text = alarmLbls[indexPath.row]
if alarmLbls[indexPath.row] == "" {
cell.alarmImg.image = UIImage(named: "alarm_off")
let alarmImgYConstraintOff = NSLayoutConstraint(item: cell.alarmImg, attribute: .CenterY, relatedBy: .Equal, toItem: cell.mainView, attribute: .CenterY, multiplier: 1, constant: 0)
alarmImgYConstraintOff.active = true
cell.layoutIfNeeded()
}
else {
cell.alarmImg.image = UIImage(named: "alarm_on")
let alarmImgYConstraintOn = NSLayoutConstraint(item: cell.alarmImg, attribute: .CenterY, relatedBy: .Equal, toItem: cell.mainView, attribute: .CenterY, multiplier: 0.75, constant: 0)
alarmImgYConstraintOn.active = true
cell.layoutIfNeeded()
}
初始佈局看起來不錯,但是當我打電話reloadItemsAtIndexPaths
上的「在」報警含有細胞,我得到指示「關」約束施加約束錯誤,在這種情況下,「上」約束休息和圖像轉移到中心。第一個if
塊似乎沒有被這些單元調用,但是,根據打印測試(僅用於從屏幕外重新加載的「關閉」單元),這是我設置這些約束的唯一位置。
我已經試過幾乎每一個迭代的解決方案,我能想到的:
- 強制
alarmImgYConstraintOff.active = false
- 通過IB設置一箇中心的約束,並將其關閉編程
- 切換「的」塊到
if
聲明 - 更改
else
到else if
將「開啓」約束的優先級設置爲高於「關閉」約束的優先級時,只會使所有「關閉」圖像在重新加載時向上移位。但是,出於某種原因,在第四次重新加載時,圖像會移回原來的居中(正確)位置。
任何想法,我在做什麼錯在這裏?
編輯:用於車削不需要約束關閉
cell.alarmLbl.text = alarmLbls[indexPath.row]
let alarmImgYConstraintOff = NSLayoutConstraint(item: cell.alarmImg, attribute: .CenterY, relatedBy: .Equal, toItem: cell.mainView, attribute: .CenterY, multiplier: 1, constant: 0)
let alarmImgYConstraintOn = NSLayoutConstraint(item: cell.alarmImg, attribute: .CenterY, relatedBy: .Equal, toItem: cell.mainView, attribute: .CenterY, multiplier: 0.75, constant: 0)
if alarmLbls[indexPath.row] == "" {
cell.alarmImg.image = UIImage(named: "alarm_off")
alarmImgYConstraintOn.active = false
alarmImgYConstraintOff.active = true
cell.layoutIfNeeded()
}
else {
cell.alarmImg.image = UIImage(named: "alarm_on")
alarmImgYConstraintOff.active = false
alarmImgYConstraintOn.active = true
cell.layoutIfNeeded()
}
初始佈局看起來很不錯,和以前一樣,但我還是儘快讓佈局的假期,因爲我重裝「開」細胞(除第一次重新加載)。例如。第二次重新加載「開啓」單元會中斷,隨後重新加載所有「開啓」和「關閉」單元(雖然對於「關閉」單元沒有可見的差異);然而,如果我先重新加載一個「off」單元,那麼在我重新加載一個「on」單元之前,什麼都不會中斷。
當你關閉一個約束時,應該關閉另一個約束。如果你嘗試過,但沒有成功,那麼你可能沒有正確地做。你可以發佈該嘗試的代碼嗎? – dan
編輯的問題包括新的代碼和結果!不幸的是,仍然沒有骰子。 – bittersweetblue