简体   繁体   English

在Xcode中将UIButton分配给UIView

[英]Assigning UIButton to UIView in Xcode

In my project i used the below code for a purpose and it is working properly. 在我的项目中,我出于以下目的使用了以下代码,并且该代码正常工作。 My code: 我的代码:

 UIView *view = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg",index]]] autorelease];

view.frame = CGRectMake(70, 80, 180, 260);
return view;

But here instead of UIImageView i would like to use UIButton,So I replaced the first lin eof above code by: 但是在这里我想使用UIButton而不是UIImageView,所以我用以下代码替换了上面代码的第一行:

  UIView *view=[[UIButton alloc] setBackgroundImage:(UIImage *)[scrollImages objectAtIndex:index] forState:UIControlStateNormal];

But at this point i am getting an error message as 但是在这一点上我收到一条错误消息

"Initializing 'UIView*_strong' with an expression of incompatible type 'void'". “使用不兼容类型'void'的表达式初始化'UIView * _strong'”。

Can anyone help me to solve this by replacing UIImageView with UIButton.... 任何人都可以通过将UIImageView替换为UIButton来帮助我解决此问题。

You should init the instance of UIButton after created it via `alloc' 通过“ alloc”创建UIButton实例后,应将其init

UIButton *button = [[UIButton alloc] init];
[button setBackgroundImage:(UIImage *)[scrollImages objectAtIndex:index] forState:UIControlStateNormal];
UIView *view = button;

You must use an init... method to complete the initialization process

- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state return nothing (void), it's certainly incompatible type with UIView. - (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state返回任何值(void),这肯定是与UIView不兼容的类型。

Like this... 像这样...

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(pressed:) forControlEvents:UIControlEventTouchUpInside];

UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg",index]];
[button setImage:image forState:UIControlStateNormal];
button.frame = CGRectMake(70, 80, 180, 260);
[self.view addSubview:button];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM