Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

iphone - Changing the position of custom UIButton in custom UITableViewCell

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.

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?

EDIT: 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Something like this:

@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 );

   }
}

Alternatively, you can attempt to do cell layout in - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...