2017-08-23 21 views
-1

我嘗試添加約束條件添加到UITableView中的基本樣式單元格,但它們不是活動的。如何在基本樣式TableView單元中添加約束條件

我用基本風格,而不是定製,因爲我需要一些行從標題開始,另一名來自cell.ImageView!.image

如果我使用自定義單元格,在沒有ImageView的,標題是反正遠離該行的左側。

截圖:

Screenshot

+0

** **請,你應該告訴我們你嘗試過什麼,以及它如何失敗。我建議你看看[這](https://youtu.be/H9NhYx9xIiU?t=273)視頻,也看到[this](https://stackoverflow.com/questions/18969355/how-to-create-a-自定義的UITableViewCell - 編程 - 使用 - 自動佈局)。您還可以搜索更多關於「如何以編程方式創建tableViewcell – Honey

+0

我失敗了,因爲我找不到任何約束與現有的鄰居對象的條件或因爲基本樣式單元約束不活躍,我不知道爲什麼。 –

回答

0

使用完全自定義單元格。甚至不打擾預定義的一個。你自己構建它,你不必擔心任何事情,你可以根據需要使用約束(只要確保它們與單元格的內容視圖相關,而不是任何其他視圖 - UITableViewCell有相當多的)。

+0

謝謝你的答案,但我不知道哪個約束會使標題移動到左側,如果沒有ImageView,我試圖將標題粘貼到圖像視圖,並且前導空格,但沒有處理。 –

0

我找到答案蘋果文檔: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html

而這個代碼工作:

import UIKit 

class ViewController: UITableViewController { 


override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return 4 
} 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "ChecklistItem", for: indexPath) 

    let label = cell.viewWithTag(1000) as! UILabel 
    let image = cell.viewWithTag(1001) as! UIImageView 
    let margins = cell.contentView.layoutMarginsGuide 

    if indexPath.row == 0 { 
     label.text = "First row" 
    } else if indexPath.row == 1 { 
     label.text = "Second row" 
     image.image = UIImage(named: "test") 
    } else if indexPath.row == 2 { 
     label.text = "Third row" 
     label.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true 

    } else if indexPath.row == 3 { 
     label.text = "Fourth row" 
    } 
    return cell 
    } 
} 

Screenshot

相關問題