在UITable滚动时自动将UI元素添加到UIStackView

问题描述 投票:1回答:5

在我的应用程序中有一个UITable。在表格单元格中我添​​加了UIStackView以在加载表格单元格时填充。

它工作正常,直到向下滚动表格,当我向上和向下滚动时,堆栈视图会添加更多元素。 (元素意味着UIButtons,我将来会用UIlabel替换它们)

我没有任何想法来解决这个问题。谢谢..

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    UIStackView *stkItems=(UIStackView *)[cell viewWithTag:8];

    for(int i=0;i<5;i++)    {
        UIButton *btn=[UIButton buttonWithType:UIButtonTypeSystem];
        [btn setTitle:@"test btn" forState:UIControlStateNormal];
        [stkItems addArrangedSubview:btn];
    }
}
ios objective-c uitableview uistackview
5个回答
4
投票

表格视图在离开屏幕时重复使用单元格。这就是你发送一条名为dequeueReusableCellWithIdentifier:的消息的原因。你永远不会从堆栈视图中取出按钮。每次重复使用单元格时,都会向堆栈视图中已有的按钮添加五个按钮。


3
投票

我有一个类似的问题,在tableview单元格中添加arrangedSubviews

这里的技巧是,在你的单元格的prepareForResue中,用removeFromSuperview从他们的超级视图中删除你的每个stackView的子视图,并且,调用removeArrangedSubview

应该是这样的:

for view in self.views {
    radioView.removeFromSuperview()
}
self.views.removeAll()

for arrangedSubview in self.stackView.arrangedSubviews {
    self.stackView.removeArrangedSubview(arrangedSubview)
}

正如Apple documentation所说:

[removeArrangedSubview]方法不会从堆栈的子视图数组中删除提供的视图;因此,视图仍显示为视图层次结构的一部分。

希望它会帮助某人;)


1
投票

从该代码看来,每次你的应用程序需要绘制一个单元格时,它会向UIStackView添加按钮,所以当一个单元格被重用时(通过dequeueReusableCellWithIdentifier)它仍然包含按钮,但是你的代码每次都会增加更多。也许您应该检查UIStackView是否有足够的按钮或清除所有按钮并添加您需要的内容。

希望这可以帮助


1
投票

我想我解决了。但我不知道它是否符合标准。

这是更新的。我已初始化并将其声明为0。

@implementation HistoryViewController
int data=0; 

并像这样更改cellForRowAtIndexPath,这样它就不会再次更新相同的stackview

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",indexPath.row);
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];


    if(data <=indexPath.row)
    {
        data=(int)indexPath.row;
        UIStackView *stkItems=(UIStackView *)[cell viewWithTag:8];
        [stkItems.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];
        for(int i=0;i<5;i++)    {
            UIButton *btn=[UIButton buttonWithType:UIButtonTypeSystem];
            [btn setTitle:@"test btn" forState:UIControlStateNormal];
            [stkItems addArrangedSubview:btn];
        }
    }



    return cell;
}

0
投票

由于单元格正在重用UIStackView,因此您必须在添加新的子视图之前删除它们。要执行此操作,请在循环之前调用以下代码并将已排列的子视图添加到UIStackView:

斯威夫特3

for view in stackView.arrangedSubviews {
    view.removeFromSuperview()
}

Objective-C的

for (UIView *view in stackView.arrangedSubviews) {
    [view removeFromSuperview];
}

*注意:如果根据Apple的评论调用[stackView removeArrangedSubview:view],它实际上并没有从接收器中完全删除它。见下面的引用:

- (void)removeArrangedSubview:(UIView *)view“从已排列的子视图列表中删除子视图而不将其作为接收者的子视图删除。要将视图作为子视图删除,请像往常一样发送-removeFromSuperview;相关的UIStackView将自动从已安排的子视图列表中删除它。“

© www.soinside.com 2019 - 2024. All rights reserved.