2016-04-28 116 views
1

我正在制作一个自定义UIControl,并且希望控件的一部分包含图像。目前,控制能够从服务器上下载的图片,我目前做这在drawRect中没有效果:将ImageView作为子视图添加到自定义UIControl中

NSURL *url = [NSURL URLWithString:self.imageData]; 
NSData *data = [NSData dataWithContentsOfURL:url]; 
UIImage *image = [UIImage imageWithData:data]; 
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.bounds]; 
imageView.image = image; 

我相信这是因为我的控制是不是添加的ImageView作为一个子视图,但我不知道该怎么做,因为这是UIControl而不是UIView。

类看起来是这样的:

@interface RDWebButton : UIControl 

/** The color of the button*/ 
@property (nonatomic) IBInspectable UIColor *buttonColor; 

#if TARGET_INTERFACE_BUILDER 
@property (nonatomic) IBInspectable NSInteger buttonShape; 
#else 
@property (nonatomic) RDShape buttonShape; 
#endif 

@end 

- (void)drawRect:(CGRect)rect { 
    // do drawing 
    NSLog(@"drawRect..."); 
    self.backgroundColor = [UIColor clearColor]; 

    [self.buttonColor setFill]; 
    switch (self.buttonShape) { 
     case RDShapeSquare: { 
      UIBezierPath *path = [UIBezierPath bezierPathWithRect:rect]; 
      [path fill]; 
      break; 
     } 
     case RDShapeRoundedRect: { 
      UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:10]; 
      [path fill]; 
      break; 
     } 
     case RDShapeCircle: { 
      UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect]; 
      [path fill]; 
      break; 
     } 
    } 
    NSURL *url = [NSURL URLWithString:self.imageData]; 
    NSData *data = [NSData dataWithContentsOfURL:url]; 
    UIImage *image = [UIImage imageWithData:data]; 
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.bounds]; 
    imageView.image = image; 
} 

所有我现在想的是让我的形象出现所绘制的形状上面。我将超类设置为UIControl而不是UIButton,因为我可能想要更改此设置以让用户拖动项目来显示菜单或其他内容,但我确信UIControl应该能够完成UIButton可以执行的所有操作。我的挑战只是让图像加载绘制的形状。

+0

什么是它的子类?的UIButton?你能告诉我们全班吗? – Echizzle

+0

增加了一些代码来澄清 – RDSpinz

回答

0

所以解决方案是你必须找到你控制在其超视图的子视图。我使用的代码是这样的:

NSURL *url = [NSURL URLWithString:self.imageData]; 
     NSData *data = [NSData dataWithContentsOfURL:url]; 
     UIImage *image = [UIImage imageWithData:data]; 
     UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.bounds.size.width * 0.25, self.bounds.size.height * 0.25, self.bounds.size.width * 0.5, self.bounds.size.height * 0.5)]; 
     imageView.image = image; 
     [self.superview.subviews.firstObject addSubview:imageView]; 
     for (UIView *view in self.superview.subviews) { 
      if (view == self) { 
       [view addSubview:imageView]; 
      } 
     } 

这使得imageview正好在我的UIControl的中心。

相关问题