我正在制作一个自定义的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可以执行的所有操作。我的挑战只是让图像加载到绘制的形状上。
答案 0 :(得分:0)
所以解决方案是你必须在superview的子视图中找到你的控制权。我使用的代码是:
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的中心。