2010-09-27 2 views
0

Хорошо, короткое сокращение моего приложения, прежде чем я объясню проблему. Мое приложение имеет два вида для своего пользовательского TableViewCell, одного frontview и одного backview (который открывается, как только вы проведите пальцем по ячейке, как и твиттер-приложение).Проблема с UIButton на subview ячейки

Anywho, я хотел иметь несколько кнопок на задней панели. Я сделал это в cellForRowAtIndexPath-method

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

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-cell - это то, что я реализовал от кого-то, кто разместил свой код.

Но, по моему мнению, на моем представлении есть UILabels noe, потому что я не добавляю их как виды, а только рисую их, используя функцию 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)]; 


} 
+0

много кодов. phew :) – vodkhang

+0

Подклассы RadioTableCellView UITableViewCell? Если это так, я думаю, что у меня есть лучший подход. –

+0

Нет, это подклассы UIView, RadioTableCell, с другой стороны, делает подкласс UITableViewCell. – Jensen2k

ответ

2

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

+0

Спасибо! :-) Это все решило! : D – Jensen2k

2

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

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

+0

Вот что я понял. Я попытался заменить drawTextInRect на addSubview, но без эффекта. – Jensen2k

+0

Вы должны разместить код с помощью addSubview, возможно, что-то не так – vodkhang

+0

Обновлен код. Посмотрите под nowTitle, я попытался добавить туда subview. – Jensen2k

0

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

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

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

UIView *currentView = button.superView; 
while (![currentView isKindOfClass:UITableViewCell] && currentView != nil) { 
    currentView = currentView.parent; 
} 

Получите вид спереди и назад (или когда-нибудь) из содержимого таблицы элементов таблицы с помощью тегов.

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 непосредственно. См. Programmatically Adding Subviews to a Cell’s Content View.

+0

Сказав все это, если вы просто хотите текст, а не фактический контроль, подход водханга - это путь. –

Смежные вопросы