6

我有一个 XIB 文件,其中包含UIControlUIScrollView元素。我想在视图中添加背景图像。我尝试在 IB 中添加一个 ImageView,但我无法让它作为背景出现,并且它模糊了控制元素。发送sendViewBack消息似乎也没有任何作用。

当我以编程方式创建 UIImageView 时,它没有显示出来。

以下是我尝试的代码:

程序化创作

UIImage *imageBackground = [UIImage imageWithContentsOfFile:@"globalbackground"];

UIImageView *backgroundView = [[UIImageView alloc] initWithImage:imageBackground];

[[self view] addSubview:backgroundView];

[[self view] sendSubviewToBack:backgroundView];

处理NIB文件

[[self view] sendSubviewToBack:background];

其中 background 是IBOutlet在头文件中声明并连接到 IB 中的 NIB 的图像视图。

我在这里缺少一个步骤吗?

4

2 回答 2

8

设置框架,不要使用sendSubviewToBack:. 如果您正在使用 UIImageViews,则必须使用[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"imageName.png"]];

UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"imageBackground"]];
backgroundView.frame = self.view.bounds;
[[self view] addSubview:backgroundView];

希望这是交易。

于 2012-01-04T08:19:02.313 回答
5
  • 不要将图像视图添加为滚动视图的子视图,它需要是层次结构顶层的单独视图,然后发送到 Z-order 的后面。
  • 您需要将滚动视图的背景设置为[UIColor clearColor],并确保滚动视图未标记为不透明。您可以在代码或界面生成器中执行此操作。
  • 不要使用imageWithContentsOfFile,然后只传递一个没有扩展名的文件名(我假设 .png) - 这可能是返回nil. 改为使用imageNamed:(在这种情况下,您不提供扩展,iOS4 及更高版本)

根据图像的性质,您还可以使用它生成颜色并将其用作滚动视图的背景颜色。我假设 self.view 是滚动视图:

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"globalBackground"]];
于 2012-01-04T08:26:46.593 回答