UIimage没有出现在iOS中的scrollview上

时间:2016-07-16 20:01:47

标签: ios objective-c iphone uiscrollview

需要水平滚动滚动视图并在其下方放置图像。 它正在水平滚动,但即使在更改背景后也看不到我的图像。请找到以下代码: -

#import "ViewController.h"

@interface ViewController () <UIScrollViewDelegate>

@property (nonatomic , weak) IBOutlet UIScrollView *scrollView;

@end

@implementation ViewController

   - (void)viewDidLoad {
[super viewDidLoad];

for(int i=0; i<5; i++) {
    UIImageView *imageView = [[UIImageView alloc]  initWithFrame:CGRectMake((self.view.window.frame.size.width/5)*i, 0, self.view.window.frame.size.width/5, 48)];
    imageView.image = [UIImage imageNamed:@"t3"];
    imageView.backgroundColor = [UIColor blackColor];
    [_scrollView addSubview:imageView];
}

_scrollView.contentSize = CGSizeMake(self.view.window.frame.size.width, 48.0f);
[self.view addSubview:_scrollView];

}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
      }

@end

2 个答案:

答案 0 :(得分:2)

在循环中设置一个断点并检查你的图像浏览的帧并检查你的图像&#34; t3&#34;实际上正在加载。

你可以改变的其他事情,

  1. 您不需要使用self.view.window.frame,只需使用self.view.frame。
  2. 您将滚动视图添加到视图中,但它是一个IBOutlet,如果您已经在故事板或xib的层次结构中拥有它,则不需要这样做。
  3. 如果您还有问题,请发表评论,祝您好运。

答案 1 :(得分:0)

问题在于self.view.window

从Apple的文件中可以说是

  

如果视图尚未添加到窗口,则此属性为nil

您还没有将self.view添加到窗口,所以如果您使用

NSLog(@"self.view.window: %@", self.view.window);

日志将是

  

self.view.window :( null)

也就是说,self.view.window.frame.size.width的值为0。


所以解决方案很简单:

使用self.view.frame.size.width代替self.view.window.frame.size.width

使用以下代码将self.view添加到窗口

[[[[UIApplication sharedApplication] windows] firstObject] addSubview:self.view]; 
相关问题