如何在tableviewcell中使标签或图像动态化?

时间:2017-01-18 16:37:18

标签: swift

我想让tableview单元格中包含动态标签或图像。我不想循环添加子视图到tableview单元格的内容视图,因为滚动时它会运行缓慢。那么有人可以帮我吗?喜欢这张图片:

Like this image

我的代码是; enter image description here

1 个答案:

答案 0 :(得分:0)

在不知道代码的上下文的情况下,这样的事情可以起作用:

注意这适用于iOS< = 8

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    @IBOutlet weak var TableVC: UITableView!

    let elements = ["item1 item2 item3","item1 item2", "item1"]



    override func viewDidLoad() {
        super.viewDidLoad()

        self.TableVC.delegate = self
        self.TableVC.dataSource = self


        self.TableVC.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        // 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.





    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

     return elements.count
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)



        cell.textLabel?.numberOfLines = 0



      cell.textLabel?.attributedText = addTextToAttribute(text: elements[indexPath.item])




        return cell
    }



    func addTextToAttribute(text : String) -> NSMutableAttributedString {


      let mutString = NSMutableAttributedString()

     let  s = text.components(separatedBy: .whitespaces)
        let attr: [String: AnyObject] = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 20)]

        for text in s {


        mutString.append(NSAttributedString(string: "-" + text + "\n", attributes: attr))
        }


        return mutString
    }

}

enter image description here