Проблема с UIButton на подпредставлении ячейки - PullRequest
0 голосов
/ 27 сентября 2010

Хорошо, короткое описание моего приложения, прежде чем я объясню проблему. У моего приложения есть два вида настраиваемой TableViewCell, один вид спереди и один вид сзади (который открывается, когда вы проводите пальцем по ячейке, очень похоже на твиттер-приложение).

Во всяком случае, я хотел бы иметь несколько кнопок на заднем плане. Я сделал это в методе cellForRowAtIndexPath

Сначала вы увидите, как я назначаю метки ячейкам. Второе, что вы увидите, это кнопка. Работает нормально.

UILabel *nextArtist = [UILabel alloc];
        nextArtist.text = @"Rihanna";
        nextArtist.tag = 4;
        [cell setNextArtist:nextArtist];

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(6 ,31, 110, 20);
        [button setImage:[UIImage imageNamed:@"radionorge.png"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(touched:) forControlEvents:UIControlEventTouchUpInside];



        [cell.backView addSubview:button];

Но проблема заключается в следующем методе.

-(void)touched:(id)sender {

    // Here i want to get the UILabels for each cell. Such as nextArtist.
    if ([sender isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)sender;
        UIView *contentView = button.superview;
        UIView *viewWithTag4 = [contentView viewWithTag:4];
        if ([viewWithTag1 isKindOfClass:[UILabel class]]) {
            UILabel *titleLabel = (UILabel *)viewWithTag4;
            NSLog(@"Label: ",titleLabel.text);
        }

    }
}

Итак, я понял, что не могу просто перейти к суперпредставлению кнопки и найти там свои ярлыки, потому что они в другом подпредставлении. Я отсканировал все свои виды, но все еще не могу найти ярлык.

Я очень новичок в этом, и подклассы ячеек TableView реализованы кем-то, кто разместил их код.

Но я предполагаю, что в моем представлении нет ни одного UILabels, потому что я не добавляю их как представления, а только рисую их с помощью функции drawTextInRect.

[nextArtist drawTextInRect:CGRectMake(boundsX+200 ,46, 110, 15)];

Я пытался добавить их в качестве подпредставлений, но безуспешно. Кто-нибудь может мне помочь?

// Еще немного кода, который вам может понадобиться, чтобы решить головоломку (здесь создаются ячейки)

@implementation RadioTableCellView
- (void)drawRect:(CGRect)rect {

    if (!self.hidden){
        [(RadioTableCell *)[self superview] drawContentView:rect];
    }
    else
    {
        [super drawRect:rect];
    }
}
@end

@implementation RadioTableCellBackView
- (void)drawRect:(CGRect)rect {

    if (!self.hidden){
        [(RadioTableCell *)[self superview] drawBackView:rect];
    }
    else
    {
        [super drawRect:rect];
    }
}

@end

@interface RadioTableCell (Private)
- (CAAnimationGroup *)bounceAnimationWithHideDuration:(CGFloat)hideDuration initialXOrigin:(CGFloat)originalX;
@end

@implementation RadioTableCell
@synthesize contentView;
@synthesize backView;
@synthesize contentViewMoving;
@synthesize selected;
@synthesize shouldSupportSwiping;
@synthesize shouldBounce;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {

        [self setBackgroundColor:[UIColor clearColor]];

        RadioTableCellView * aView = [[RadioTableCellView alloc] initWithFrame:CGRectZero];
        [aView setClipsToBounds:YES];
        [aView setOpaque:YES];
        [aView setBackgroundColor:[UIColor clearColor]];
        [self setContentView:aView];
        [aView release];

        RadioTableCellBackView * anotherView = [[RadioTableCellBackView alloc] initWithFrame:CGRectZero];
        [anotherView setOpaque:YES];
        [anotherView setClipsToBounds:YES];
        [anotherView setHidden:YES];
        [anotherView setBackgroundColor:[UIColor clearColor]];
        [self setBackView:anotherView];
        [anotherView release];

        // Backview must be added first!
        // DO NOT USE sendSubviewToBack:

        [self addSubview:backView];
        [self addSubview:contentView];

        [self setContentViewMoving:NO];
        [self setSelected:NO];
        [self setShouldSupportSwiping:YES];
        [self setShouldBounce:YES];
        [self hideBackView];
    }

    return self;
}

Пожалуйста, помогите мне или, по крайней мере, укажите мне направление или два!

////////////////////////// Обновлен новым кодом: Это внутри моего RadioCustomCell, подкласса UIView. Это здесь UILabels нарисованы

#import "RadioCustomCell.h"

@implementation RadioCustomCell
@synthesize nowTitle,nowArtist,nextTitle,nextArtist,ChannelImage;

// Setting the variables

- (void)setNowTitle:(UILabel *)aLabel {

    if (aLabel != nowTitle){
        [nowTitle release];
        nowTitle = [aLabel retain];
        [self setNeedsDisplay];
    }
}

- (void)setNowArtist:(UILabel *)aLabel {

    if (aLabel != nowArtist){
        [nowArtist release];
        nowArtist = [aLabel retain];
        [self setNeedsDisplay];
    }
}
- (void)setNextTitle:(UILabel *)aLabel {

    if (aLabel != nextTitle){
        [nextTitle release];
        nextTitle = [aLabel retain];
        [self setNeedsDisplay];
    }
}
- (void)setNextArtist:(UILabel *)aLabel {

    if (aLabel != nextArtist){
        [nextArtist release];
        nextArtist = [aLabel retain];
        [self setNeedsDisplay];
    }
}

- (void)setChannelImage:(UIImage *)aImage {

    if (aImage != ChannelImage){
        [ChannelImage release];
        ChannelImage = [aImage retain];
        [self setNeedsDisplay];
    }
}

- (void)drawContentView:(CGRect)rect {

    CGContextRef context = UIGraphicsGetCurrentContext();

    //UIColor * backgroundColour = [UIColor whiteColor];

    UIColor *backgroundColour = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"CellBackground.png"]];

    [backgroundColour set];
    CGContextFillRect(context, rect);

    CGRect contentRect = self.contentView.bounds;
    CGFloat boundsX = contentRect.origin.x;

    [ChannelImage drawInRect:CGRectMake(boundsX+120 ,25, 75, 35)];

    nowTitle.enabled = YES;
    nowTitle.textAlignment = UITextAlignmentCenter;
    nowTitle.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size: 14.0];
    nowTitle.textColor = [UIColor blackColor];
    nowTitle.backgroundColor = [UIColor clearColor];
    //[nowTitle drawTextInRect:CGRectMake(boundsX+6 ,31, 110, 20)];

    // Trying to add a subview instead of drawing the text
    nowTitle.frame = CGRectMake(boundsX+6 ,31, 110, 20);
    [self addSubview:nowTitle];
    // I have also tried adding it to super, no effect.

    nowArtist.enabled = YES;
    nowArtist.textAlignment = UITextAlignmentCenter;
    nowArtist.font = [UIFont fontWithName:@"HelveticaNeue" size: 10.0];
    nowArtist.textColor = [UIColor blackColor];
    nowArtist.backgroundColor = [UIColor clearColor];
    [nowArtist drawTextInRect:CGRectMake(boundsX+6 ,46, 110, 15)];

    nextTitle.enabled = NO;
    nextTitle.textAlignment = UITextAlignmentCenter;
    nextTitle.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size: 12.0];
    [nextTitle drawTextInRect:CGRectMake(boundsX+200 ,31, 110, 20)];

    nextArtist.enabled = NO;
    nextArtist.textAlignment = UITextAlignmentCenter;
    nextArtist.font = [UIFont fontWithName:@"HelveticaNeue" size: 9.0];
    [nextArtist drawTextInRect:CGRectMake(boundsX+200 ,46, 110, 15)];


}

Ответы [ 3 ]

2 голосов
/ 27 сентября 2010

Вы просто забыли инициализировать UILabel в самой первой строке кода.:)

2 голосов
/ 27 сентября 2010

На первый взгляд, я могу быть уверен, что если вы нарисуете текст (а текст не является надписью), то в вашей ячейке вообще не будет UILabel.Вы можете игнорировать этот способ.

Итак, если у вас нет UILabel, как вы можете получить текст.Поскольку ваш contentView действительно RadioTableCellView, то это не сложно.В вашем классе просто публикуйте свойство с именем nextArtist.Когда ваша кнопка нажата, ищите contentView (вызывая какое-то суперпредставление), приведите его к RadioTableCellView, затем получите nextArtist из

0 голосов
/ 27 сентября 2010

Не написав кучу кода, вот мое лучшее предположение.

Вам нужно будет присвоить теги aView и anotherView в вашем методе initWithStyle :.Я собираюсь предположить, что у вас есть пара констант: BACK_VIEW_TAG и FRONT_VIEW_TAG.

В вашем методе touched: поднимайтесь по иерархии представлений, пока не найдете UITableViewCell.

Получить вид спереди и вид сзади (или любой другой вид) из contentView ячейки таблицы, используя теги.

if (currentView != nil) {
    UITableViewCell *cellView = (UITableViewCell *)currentView)
    UIView *cellContentView = cellView.contentView;
    UIView *backView = [cellContentView viewWithTag:BACK_VIEW_TAG];
    UIView *frontView = [cellContentView viewWithTag:FRONT_VIEW_TAG];

    // Get other views from frontView and backView using viewWithTag:.
}

Обратите внимание, что следует добавлять представления в contentView вашего подкласса UITableViewCell, а неUITableViewCell напрямую.Подробнее см. Программное добавление подпредставлений в представление содержимого ячейки .

...