繁体   English   中英

在Xcode中将UIButton分配给UIView

[英]Assigning UIButton to UIView in Xcode

在我的项目中,我出于以下目的使用了以下代码,并且该代码正常工作。 我的代码:

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

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

但是在这里我想使用UIButton而不是UIImageView,所以我用以下代码替换了上面代码的第一行:

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

但是在这一点上我收到一条错误消息

“使用不兼容类型'void'的表达式初始化'UIView * _strong'”。

任何人都可以通过将UIImageView替换为UIButton来帮助我解决此问题。

通过“ 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返回任何值(void),这肯定是与UIView不兼容的类型。

像这样...

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