【发布时间】:2011-06-04 02:06:12
【问题描述】:
以下代码有问题。
我想在多个按钮上使用一个 UIImageView,对我来说只定义一次 UIImageView 并根据需要多次使用它似乎是合乎逻辑的。
如果我尝试将 imgView1 附加到两个不同的按钮,则只显示其中一个。
我可以通过使用注释掉的 imgView2 来解决这个问题。
但我必须这样做似乎很愚蠢。为什么我不能只拥有一个 UIImageView,然后根据需要将其添加到尽可能多的视图中?
// This will not allow me to use imgView1 more than once and only one of the imgViews/buttons is displayed.
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"some_image" ofType:@"png"]];
UIImageView *imgView1 = [[UIImageView alloc] initWithImage:image];
//UIImageView *imgView2 = [[UIImageView alloc] initWithImage:image];
CGRect frame = CGRectMake(10, 10, 70, 72);
UIButton *h=[UIButton buttonWithType:UIButtonTypeCustom];
[h setFrame:frame];
[h insertSubview:imgView1 atIndex:1];
frame = CGRectMake(100, 10, 70, 72);
UIButton *h2=[UIButton buttonWithType:UIButtonTypeCustom];
[h2 setFrame:frame];
[h2 insertSubview:imgView1 atIndex:1];
[self.view addSubview:h];
[self.view addSubview:h2];
[imgView1 release];
//[imgView2 release];
编辑:
上下文
我为我的问题添加了一些上下文
我正在尝试创建一个带有渐变背景层的图像,该层位于实际图像后面,并且是此问题的后续问题(URL:Making a Transparent image button with bgcolor)
虽然我可以简单地使用setImage,但它不会将渐变背景层放入背景中。
例如:
int fullFrameX = 25;
int extFrameX = fullFrameX + 3;
CGRect fullFrame;
CGRect frame;
fullFrame = CGRectMake(fullFrameX, 10, 70,72);
frame = CGRectMake(extFrameX, 13, 63,65);
UIButton *h=[UIButton buttonWithType:UIButtonTypeCustom];
[h setFrame:fullFrame];
[[h layer] setMasksToBounds:YES];
//[h setBackgroundImage:image forState:UIControlStateNormal];
[h setImage:image forState:UIControlStateNormal];
[h setShowsTouchWhenHighlighted:YES];
[h setClipsToBounds:YES];
CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];
[gradientLayer setBounds:frame];
[gradientLayer setPosition:CGPointMake([h bounds].size.width/2, [h bounds].size.height/2)];
[gradientLayer setColors:[NSArray arrayWithObjects:
(id)[[UIColor colorWithRed:255 green:0 blue:255 alpha:0]CGColor],(id)[[UIColor blackColor] CGColor], nil]];
[[h layer] insertSublayer:gradientLayer atIndex:1];
//[h insertSubview:imgView atIndex:1];
[h setTag:0];
[h addTarget:self action:@selector(btnSelectColor:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:h];
//[imgView release];
[gradientLayer release];
这是我的原始代码(来自上一个问题)的 canabalised 版本,它的作用是将图像置于与我的渐变背景相同的级别。
在我之前的问题中,我提到了使用 UIImageViews 完成大部分繁重工作的答案,除了我面临的问题是我必须创建多个 UIImageViews 当我真的只需要创建一次时。
这个想法是有 4 个按钮,每个按钮都有一个彩色背景,用户可以从中单击以选择他们的配色方案。
这有点难以解释,但我会试着把它分解成一个列表。
- 图像(头像)是顶层
- 渐变背景在背景中并被强制转换为
frame - 整个对象都是可点击的
- 每次我想使用它时我只需要初始化 1 个 UIImageView,但我不得不创建同一个 UIImageView 的多个副本。
我希望这能澄清我的问题的背景。
【问题讨论】:
标签: uiimageview uibutton