【问题标题】:Two uibutton shown in TableView Cell when device rotated设备旋转时 TableView Cell 中显示的两个 uibutton
【发布时间】:2016-10-17 12:00:45
【问题描述】:

我正在使用带有 TableViewCell 的 TableView。我以编程方式向单元格添加了 ImageView、Text 和 uibutton。按钮的框架针对纵向和横向设置不同。但是当设备从纵向旋转到横向时,会显示两个按钮而不是一个。

我尝试在横向模式按钮不起作用时删除按钮。

switch ([indexPath section])
{

    case 0:
    {
        cell.imageView.image = [UIImage imageNamed:@"active.png"];
        cell.textLabel.text = @"Application Name";
        self.uninstallApplicationButton = [[UIButton alloc] init];
        self.uninstallApplicationButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [self.uninstallApplicationButton setTitle:@"Install" forState: UIControlStateNormal];
        [self.uninstallApplicationButton setBackgroundColor:[UIColor brownColor]];

        UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

        if (device == UIUserInterfaceIdiomPhone)
        {
            if (UIInterfaceOrientationIsLandscape(orientation))
            {
               self.uninstallApplicationButton.frame = CGRectMake(490.0, 25.0, 65.0, 30.0);
            }
            else if(UIInterfaceOrientationIsPortrait(orientation))
            {
               self.uninstallApplicationButton.frame = CGRectMake(250.0, 25.0, 65.0, 30.0);

            }
        }

        else if(device == UIUserInterfaceIdiomPad)
        {
            self.uninstallApplicationButton.frame = CGRectMake(600.0, 25.0, 150.0, 30.0);
        }

    }
    [cell.contentView addSubview:uninstallApplicationButton];
        break;

【问题讨论】:

  • 请附上相关代码。
  • @Caleb 我已经添加了代码。
  • 这段代码你在哪里写的?它可能会运行不止一次。
  • 这段代码在哪里?
  • 代码在 cellForRowAtIndexPath 中。

标签: ios objective-c uitableview uibutton uiinterfaceorientation


【解决方案1】:

您说代码在您的-cellForRow(at:) 方法中。由于表视图重用了它们的单元格,您的代码必须考虑到它正在配置的单元格可能之前已经配置过。一个好的方法是避免在此方法中向单元格添加任何按钮或其他视图,而是将它们添加到情节提要中。如果您必须向单元格添加视图,您应该删除之前添加的任何视图,或者只是重复使用它们以避免再次添加它们。

【讨论】:

    【解决方案2】:

    您需要在 alloc init 之前从其父视图中删除按钮。

    【讨论】:

    • 它不工作。它会删除按钮,但不会再次将其添加到视图中。
    • 从您的代码中删除这一行:self.uninstallApplicationButton = [[UIButton alloc] init];
    • 另请参阅此链接以了解在 tableview 单元格中添加按钮的过程:stackoverflow.com/questions/7721364/…
    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    相关资源
    最近更新 更多