Хорошо, короткое сокращение моего приложения, прежде чем я объясню проблему. Мое приложение имеет два вида для своего пользовательского 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)];
}
много кодов. phew :) – vodkhang
Подклассы RadioTableCellView UITableViewCell? Если это так, я думаю, что у меня есть лучший подход. –
Нет, это подклассы UIView, RadioTableCell, с другой стороны, делает подкласс UITableViewCell. – Jensen2k