所以我在我的项目和子视图中创建了一个子视图,我只想绘制一个简单的文本。我在主要故事板上创建了一个子视图,并将其引用到我的CustomView。将其大小设置为我的自定义视图大小。这是我的代码段。
自定义视图确实显示为红色,就像我设置它的显示方式一样,然而,其中的文本(" Hello world")并没有显示出来。我现在一直在查看代码,但无法弄清楚我做错了什么。我真的需要帮助。有人会告诉我该怎么做?谢谢。
ViewController.h
@interface ViewController : UIViewController
@property(retain, nonatomic) UIView *subView;
@end
ViewController.m
@interface ViewController()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
CustomView.h
@interface CustomView : UIView
@property(retain, nonatomic)IBOutlet UIView* view;
@end
CustomView.m
@implementation CustomView
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
// how to draw text in here
[super drawRect:rect];
// Initialize a graphics context in IOS
CGContextRef context = UIGraphicsGetCurrentContext();
// Flip the coordinate
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// ???????
// Initialize string
CFStringRef string = CFSTR("Hello world");
// Initialize font
CTFontRef font = CTFontCreateWithName((CFStringRef)@"Helvetica", 16.0f, nil);
CFStringRef keys[] = {kCTFontAttributeName};
CFTypeRef values[] = {font};
CFDictionaryRef attributes = CFDictionaryCreate(kCFAllocatorDefault, (const void **) &keys, (const void **) &values, sizeof(keys) / sizeof(keys[0]), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFAttributedStringRef attrString = CFAttributedStringCreate(kCFAllocatorDefault, string, attributes);
CFRelease(string);
CFRelease(attributes);
CTLineRef line = CTLineCreateWithAttributedString(attrString);
// Set text position and draw the line into the graphics context
CGContextSetTextPosition(context, 10, 10);
CTLineDraw(line, context);
CFRelease(line);
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if(self)
{
// 1. load the .xib file
[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil];
// 2. add the subview
self.view.backgroundColor = [UIColor redColor];
[self addSubview:self.view];
}
return self;
}
@end
答案 0 :(得分:0)
我尝试了你的代码,除了使用xibs,它完美无缺。顺便问一下,你在哪里将customView放在viewController.view中?