【问题标题】:Add ImageView as a subview within a custom UIControl将 ImageView 添加为自定义 UIControl 中的子视图
【发布时间】:2016-08-23 15:10:47
【问题描述】:

我正在制作自定义 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。

类如下所示:

@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 可以做的所有事情以及更多。我的挑战只是让图像加载到绘制的形状上。

【问题讨论】:

  • 它是什么的子类?按钮?你能带我们看看全班吗?
  • 添加了一些代码来澄清

标签: ios uiimageview uicontrol


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2017-01-12
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    相关资源
    最近更新 更多