Changing the position of custom UIButton in custom UITableViewCell

后端 未结 7 792
[愿得一人]
[愿得一人] 2020-12-10 22:49

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 di

相关标签:
7条回答
  • 2020-12-10 23:24

    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

    0 讨论(0)
提交回复
热议问题