使用按钮触发器将didFinishLaunchingWithOptions:方法移动到viewcontroller方法

时间:2013-01-13 15:51:20

标签: ios cocoa-touch

我在AppDelegate.h / .m中使用了以下代码,但无法将其更改为在ViewController中使用触发它的按钮。

@implementation BSViewController

@synthesize imageView;
@synthesize workingImage;
- (IBAction) chooseImage:(id) sender {

    UIImage* testCard = [UIImage imageNamed:@"ipad 7D.JPG"];
    CGImageRef num = CGImageCreateWithImageInRect([testCard CGImage],CGRectMake(532, 0, 104, 104));
    UIGraphicsBeginImageContext(CGSizeMake( 250,650));
    CGContextRef con = UIGraphicsGetCurrentContext();
    UIImage* im = UIGraphicsGetImageFromCurrentImageContext();
    CGContextDrawImage(con, CGRectMake(0, 0, 13, 13) ,num);
    UIGraphicsEndImageContext();
    CGImageRelease(num);

    UIImageView* iv = [[UIImageView alloc] initWithImage:im];
    [self.imageView addSubview: iv];
    iv.center = self.imageView.center;
    [iv release];

我在模拟器中看到名为“选择图像”的按钮,但我看不到那里的图像。

2 个答案:

答案 0 :(得分:0)

您尚未将self.imageView添加到任何视图中。 你需要

[self.view addSubview:self.imageView];

显示您的imageView。

答案 1 :(得分:0)

我能够让它发挥作用,但让我先问你一些假的问题。您可以跳过这些并直接跳到最后寻找答案:

  • 之前有效吗?
  • 你为什么不使用ARC?
  • 您是否已使用Interface Builder将chooseImage:链接到按钮,还是以编程方式?我有时会忘记这个基本步骤,当然没有任何作用:)
  • 为什么要将iv添加为self.imageView的子视图,而不仅仅是更改self.imageView的图像属性。了解这一点对于正确回答可能很有用。
  • 假设您有充分的理由将iv添加为子视图,请注意iv.center = self.imageView.center这些中心位于两个不同的坐标系中。
    形成Apple Documentation

      

    中心在其超视图的坐标系内指定   并以分数衡量。设置此属性会更改值   相应的框架属性。

  •   
  修改:要检查的其他事项

  • self.imageView是否存在?我的意思是,您是否已将其添加到IB并将其链接到IBOutlet,或以编程方式对其进行定义?
  • chooseImage:中添加一个断点并逐步完成,确保您在那里生成的对象不是nil
  • 测试:尝试self.imageView setImage:im代替self.imageView addSubview:iv,即使它不是您想要做的,如果其他一切都没问题,您应该看到图像。

如果切换
的顺序,它会起作用 UIImage* im = UIGraphicsGetImageFromCurrentImageContext();

CGContextDrawImage(con, CGRectMake(0, 0, 13, 13) ,num);

否则,您将要求使用上下文的内容创建im,而不会在其中绘制任何内容。

然后代码将成为:

UIImage* testCard = [UIImage imageNamed:@"ipad 7D.JPG"];
CGImageRef num = CGImageCreateWithImageInRect([testCard CGImage],CGRectMake(532, 0, 104, 104));
UIGraphicsBeginImageContext(CGSizeMake( 250,650));
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextDrawImage(con, CGRectMake(0, 0, 13, 13) ,num);
UIImage* im = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRelease(num);

希望它有所帮助。 :d

相关问题