2017-08-23 25 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

相关问题