简体   繁体   中英

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:

  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'".

Can anyone help me to solve this by replacing UIImageView with UIButton....

You should init the instance of UIButton after created it via `alloc'

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.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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