将 ImageView 添加为自定义 UIControl 中的子视图

Add ImageView as a subview within a custom UIControl

我正在制作自定义 UIControl,我希望该控件的一部分包含图像。目前,该控件能够从服务器下载图像,而我目前在 drawRect 中这样做没有效果:

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。

class 看起来像这样:

@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;
}

我现在只想让我的图像出现在绘制的形状上方。我将 superclass 设置为 UIControl 而不是 UIButton 因为我可能想更改它让用户拖动项目以显示菜单或其他东西,但我很确定 UIControl 应该能够做所有 UIButton可以做更多。我的挑战只是让图像加载到绘制的形状上。

因此解决方案是您必须在其父视图的子视图中找到您的控件。我使用的代码是这样的:

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];
            }
        }

这会将图像视图置于我的 UIControl 的中心。