OGeek|极客世界-中国程序员成长平台

标题: ios - 将 ImageView 添加为自定义 UIControl 中的 subview [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 16:11
标题: ios - 将 ImageView 添加为自定义 UIControl 中的 subview

我正在制作自定义 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 添加为 subview ,但我不知道该怎么做,因为这是 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)drawRectCGRect)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;
}

我现在只想让我的图像出现在绘制的形状上方。我将父类(super class)设置为 UIControl 而不是 UIButton 因为我可能想要更改它以让用户拖动项目以显示菜单或其他内容,但我很确定 UIControl 应该能够完成 UIButton 可以做的所有事情以及更多。我的挑战只是让图像加载到绘制的形状上。



Best Answer-推荐答案


所以解决方案是您必须在其父 View 的 subview 中找到您的控件。我使用的代码是这样的:

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 的中心。

关于ios - 将 ImageView 添加为自定义 UIControl 中的 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36921694/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4