在自定义UITableViewCell中更改自定义UIButton的位置 [英] Changing the position of custom UIButton in custom UITableViewCell

查看:181
本文介绍了在自定义UITableViewCell中更改自定义UIButton的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要动态更改UIButton的位置。我在 cellForRowAtIndexPath:中执行此操作。我改变了该方法中按钮的框架。最初显示表时不显示更改。但是当我滚过细胞并返回细胞时,它会显示出来。同样,当我第一次滚动到最初不可见的单元格时,没有任何变化。当我第二次滚动到它时发生更改。

I need to change the position of UIButton dynamically. I do this in cellForRowAtIndexPath:. I alter the frame of the button in that method. The change is not displayed when the table is initially displayed. But when I scroll past the cells and come back to it, it gets displayed. Similarly, when I first scroll to cells not visible initially, there is no change. The change occurs when I scroll to it the second time.

我在自定义按钮上尝试了 setNeedsDisplay:和表格视图。我甚至在 willDisplayCell:forRowAtIndexPath:中完成了这项工作。我如何解决这个问题?

I have tried setNeedsDisplay: on both the custom button and the table view. I have done this even in willDisplayCell:forRowAtIndexPath:. How do I solve this?

编辑:我忘了提到我从nib文件加载UITableViewCell。以下是调整框架大小的代码。

I forgot to mention that I am loading the UITableViewCell from a nib file. Here is the code to resize the frame.

label1.text  = //text from some source
label1.text = [label1.text stringByAppendingString:@"  |"];
[label1 sizeToFit];
CGRect frameAfterResize=label1.frame;
float x=frameAfterResize.origin.x+frameAfterResize.size.width;
button.frame=CGRectMake(x+2, button.frame.origin.y, button.frame.size.width,button.frame.size.height);


推荐答案

创建自己的UITableViewCell子类。在init方法中创建单元格的contentView并将其添加到单元格中,或者通过访问者属性创建并添加它。覆盖layoutSubviews并根据需要设置按钮。

Make your own UITableViewCell subclass. Create and add the button to the cell's contentView in your init method, or create and add it lazily via an accessor property. Override layoutSubviews and postion the button as desired.

这样的事情:

@implementation MyCustomCell

- (void) init
{
    self = [super initWithStyle: UITableViewCellStyleDefault reuseIdentifier: nil];
    if ( self != nil )  
    {
         _myButton = [[UIButton buttonWithType: UIButtonTypeRoundedRect] retain];
         [self.contentView addSubview: _myButton];
    }

    return self;
}

- (void) layoutSubviews
{
    [super layoutSubviews];

    // dynamic layout logic:
    if ( ... )
    {

         _myButton.frame = CGRectMake( 10, 10, 100, 30 );
    }
    else 
   {
         _myButton.frame = CGRectMake( 20, 10, 50, 30 );

   }
}

或者,你可以尝试做中的单元格布局 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

这篇关于在自定义UITableViewCell中更改自定义UIButton的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆