【问题标题】:Setting Background Image Programmatically In A Xib在 Xib 中以编程方式设置背景图像
【发布时间】:2012-02-02 04:04:16
【问题描述】:

我有一个 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];

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

这里有没有我遗漏的步骤?

【问题讨论】:

    标签: ios cocoa-touch uiview uiimageview uicontrol


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

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

    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"globalBackground"]];
    

    【讨论】:

      【解决方案2】:

      设置框架,不要使用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];
      

      希望这是交易。

      【讨论】:

      • 如果还有其他 UI 组件,请确保使用 insertSubView,如下所示:[self.view insertSubview:backgroundView atIndex:0];
      猜你喜欢
      • 2016-06-12
      • 1970-01-01
      • 2011-10-08
      • 2011-04-13
      • 2023-03-17
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多