动态细胞高度问题

时间:2017-08-20 04:20:38

标签: ios swift xcode uitableview swift3

我有一个动态单元格,每个单元格底部图像下面有两个图像和两个按钮。标签的大小取决于标签中的行数,可以是任何内容。我在cellForRowAt indexPath中获得了标签的文字。在我的viewDidLoad()中,我已经通过使用它来设置动态单元格:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 265

问题:当标签超过1行时,单元格高度的大小不会改变。在两个实例中它只有正确的大小:1)当我刷新表时。 2)当我向下滚动时,破碎的单元格不在视图中,然后当我向上滚动时,破碎的单元格位于正确的位置。

我尝试了什么:经过几个小时的尝试来解决这个问题后,有许多消息来源说了同样的事情:1)确保所有物品都有所有物品的限制双方(我这样做,同样的问题发生了)。 2)唯一的另一个人说要使用UITableViewAutomaticDimensionestimatedRowHeight(我有)。

我如何解决这个或我错过了什么?

编辑:我在获得哪种类型的单元格之后调用cellForRowAt indexPath中的标签文本(我有3个,他们都做不同的事情)。这是代码:

    func loadNews() {        
            //start finding followers
            let followQuery = PFQuery(className: "Follow")
            followQuery.whereKey("follower", equalTo: PFUser.current()?.objectId! ?? String())
            followQuery.findObjectsInBackground { (objects, error) in
                if error == nil {

                    self.followArray.removeAll(keepingCapacity: false)

                    //find users we are following
                    for object in objects!{
                        self.followArray.append(object.object(forKey: "following") as! String)
                    }
                    self.followArray.append(PFUser.current()?.objectId! ?? String()) //so we can see our own post


                    //getting related news post
                    let newsQuery = PFQuery(className: "News")
                    newsQuery.whereKey("user", containedIn: self.followArray) //find this info from who we're following
                    newsQuery.limit = 30
                    newsQuery.addDescendingOrder("createdAt")
                    newsQuery.findObjectsInBackground(block: { (objects, error) in
                        if error == nil {     
                            //clean up
                            self.newsTypeArray.removeAll(keepingCapacity: false)
                            self.animalArray.removeAll(keepingCapacity: false)
                            self.newsDateArray.removeAll(keepingCapacity: false)

                            for object in objects! {                            
                                self.newsTypeArray.append(object.value(forKey: "type") as! String) //get what type (animal / human / elements)

                                self.animalArray.append(object.value(forKey: "id") as! String) //get the object ID that corresponds to different class with its info
                                self.newsDateArray.append(object.createdAt) //get when posted
                            }
                            self.tableView.reloadData()
                        } else {
                            print(error?.localizedDescription ?? String())
                        }
                    })
                } else {
                    print(error?.localizedDescription ?? String())
                }
            }   
        }



        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let type = newsTypeArray[indexPath.row]

    if type == "element" {
      //fills cell just like animal one
    } else if type == "human" {
      //fills cell just like animal one

    } else { //its an animal cell

                            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! AnimalCell
                            let query = query(className: "Animals")
                            query.whereKey("objectId", equalTo: animalArray[indexPath.row])
                            query.limit = 1
                            query.findObjectsInBackground(block: { (objects, error) in
                                if error == nil {                            
                                    for object in objects! {

                                        let caption = (object.object(forKey: "caption") as! String)
                                        cell.captionLabel.text = caption

                                    }                               
                                } else {
                                    print(error?.localizedDescription ?? String())
                                }
                            })
           return cell
        }
    }

2 个答案:

答案 0 :(得分:1)

1。检查您是否在单元格中使用了正确的constraints

<强> 2 即可。实现这些UITableViewDelegate方法:

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

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

删除这两行:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 265

<强>截图:

<强> 1。查看层次结构:Image1 - &gt;标签 - &gt; Image2 - &gt; Button1 - &gt; BUTTON2

enter image description here

<强> 2。输出

enter image description here

如果它不起作用仍然存在:

在您的自定义preferredMaxLayoutWidth中提供UILabel UITableViewCell,即

override func awakeFromNib()
{
    super.awakeFromNib()
    self.label.preferredMaxLayoutWidth = UIScreen.main.bounds.width //Provide here the calculated width of your label
}

UITableViewDataSource方法:

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableCell
    if indexPath.row == 0
    {
        cell.label.text = "When the label is more than 1 line, the size of the height of the cell does not change."
    }
    else
    {
        cell.label.text = "When the label is more than 1 line, the size of the height of the cell does not change. It only chances to the correct size in two instances: 1) When I refresh the table. 2) when I scroll down where the broken cell is not in the view then when I scroll back up the broken cell is at the correct position."
    }
    return cell
}

答案 1 :(得分:0)

这听起来像是在加载初始表数据后设置标签的内容(可能使用后台方法从网络中获取值?)。

如果是这种情况,您可以使用UITableView.reloadRows(at:with:)方法重新加载表格中的那个单元格。请参阅:https://developer.apple.com/documentation/uikit/uitableview/1614935-reloadrows

例如:tableView.reloadRows(at: [indexPathToCell], with: .automatic)

相关问题