不兼容的指针类型分配从标签视图的UILabel
问题描述:
我一直在这里做的事情使用Objective-C的,但我在这个语言初学者,这就是我所做的:不兼容的指针类型分配从标签视图的UILabel
我已经创建了两个UIView类并将它们命名为LabelView和ButtonView。我想要做的是当我触摸标签文本更改的按钮。我已经给出了我所做的代码。
当我触摸我创建的按钮时出现错误。
错误: “ - [LABELVIEW的setText:]:无法识别的选择发送到实例0x7b66cf80”
警告就行:self.cslbl_ = lblView; - “从标签视图分配给uilabel的不兼容指针类型”。
- (void)viewDidLoad {
LabelView *lblView = [[LabelView alloc] init];
[lblView setFrame:CGRectMake(10, 100, 300, 50)];
//lblView.backgroundColor = [UIColor redColor];
self.cslbl_ = lblView;
[self.view addSubview:lblView];
ButtonView *btnView = [[ButtonView alloc] initWithFrame:CGRectMake(110, 200, 100, 50)];
SEL target = @selector(changeText:);
[btnView setSelector:self selector:target];
[self.view addSubview:btnView];
}
-(void) changeText:(UIButton *)btn {
static int k = 0;
if (k%2 == 0)
{
[self.cslbl_ setText:@"Apple is a healthy fruit"];
}
else
{
[self.cslbl_ setText:@"Apple"];
}
NSLog(@"Click value is %d",k);
k++;
}
自定义标签类
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
UILabel *myLbl = [[UILabel alloc] init];
myLbl.frame = CGRectMake(0, 0, 300, 50);
//myLbl.backgroundColor = [UIColor blueColor];
myLbl.text = @"Apple";
self.lbl_ = myLbl;
[self addSubview:myLbl];
}
return self;
}
自定义按钮
-(id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
UIButton *myBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
[myBtn setTitle:@"Touch" forState:UIControlStateNormal];
[myBtn setTitle:@"Touched" forState:UIControlStateHighlighted];
myBtn.backgroundColor = [UIColor grayColor];
self.btn_ = myBtn;
[self addSubview:myBtn];
}
return self;
}
- (void)setSelector:(UIViewController *)vc selector:(SEL)changeText
{
[btn_ addTarget:vc action:changeText forControlEvents:UIControlEventTouchUpInside];
}
答
虽然问题并不清楚,但似乎是你的self.cslbl_是一个UILabel和你给它分配lblView哪种类型的UIView,这就是你得到警告的原因。
而且您正在尝试将TextText设置为LabelView,这又不是UILabel类型,因此您会崩溃。
首先你LabelView应该是UILabel的子类而不是UIView,但如果你的需求是你的需求,那么你应该使用下面的代码。
自定义标签类
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
UILabel *myLbl = [[UILabel alloc] init];
myLbl.frame = CGRectMake(0, 0, 300, 50);
[myLb1 setTag:1];
//myLbl.backgroundColor = [UIColor blueColor];
myLbl.text = @"Apple";
self.lbl_ = myLbl;
[self addSubview:myLbl];
}
return self;
}
在viewDidLoad中
LabelView *lblView = [[LabelView alloc] init];
[lblView setFrame:CGRectMake(10, 100, 300, 50)];
self.cslbl_ = (UILabel*)[lblView viewWithTag:1];
[self.view addSubview:lblView];
现在你可以设置文字到您self.cslbl_
问题不是clear..what是自我的类型。 cslbl_? – pankaj 2014-10-20 14:25:47
你是什么意思与self.cslbl_ = lblView.Say请更好你想做什么。或者如果你想做的声明UILabel等于与其他UILabel设置只有cslbl_ = lblView。 – 2014-10-20 14:30:09
你为什么试图将'UIView'创建一个标签和一个按钮?这就是'UILabel'和'UIButton'类的用途。这个错误发生是因为你试图在你的'UIView'('LabelView')的子类上设置文本,它不知道如何处理文本。 – ravron 2014-10-20 14:44:59