我正在尝试使用drawAtPoint:point withAttributes:attrs
方法将字符串附加到 View ,但是该字符串在 View 内的任何地方都看不到,或者至少我看不到它(可能是颜色与 View 相同,白色)。
以下代码是我在 View Controller 的 viewDidLoad
中使用的代码:
NSMutableDictionary *stringAttributes = [[NSMutableDictionary alloc] init];
[stringAttributes setObject:[UIColor redColor]forKey: NSForegroundColorAttributeName];
NSString *someString = [NSString stringWithFormat:@"%@", @"S"];
[someString drawAtPoint:CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2) withAttributes: stringAttributes];
我做错了什么?
编辑:在遵循@rokjarc的建议后,我创建了一个带有drawRect
方法的 View Controller ,该方法将字符串添加到当前上下文:
#import <Foundation/Foundation.h>
@interface XYZSomeView : UIView
@end
#import "XYZSomeView.h"
#import "NSString+NSStringAdditions.h"
@implementation XYZSomeView
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
NSMutableDictionary *stringAttributes = [[NSMutableDictionary alloc] init];
[stringAttributes setObject:[UIColor redColor]forKey: NSForegroundColorAttributeName];
NSString *someString = [NSString stringWithFormat:@"%@", @"S"];
[someString drawAtPoint:CGPointMake(rect.origin.x, rect.origin.y) withAttributes: stringAttributes];
NSLog(@"%@", someString);
CGContextRestoreGState(context);
}
@end
在我的 Root View Controller 中,我初始化了XYZSomeView
:
#import "XYZRootViewController.h"
#import "XYZSomeView.h"
@implementation XYZRootViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
XYZSomeView *someView = [[XYZSomeView alloc] init];
[self.view addSubview:someView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
NSLog(@"%@", @"XYZRootViewController reveived memory warning");
}
@end
问题是我的 drawRect
没有被调用,是因为我必须自己调用它吗?我认为这个方法应该在初始化时调用,而不必我调用它。
最佳答案
您需要引用当前图形上下文才能使用此函数:docs 。 viewDidLoad:
中没有此引用。通常这是在drawRect:
内完成的。有多种方法可以在生成屏幕外内容时使用它 - 但这似乎不符合您的需求。
如果您想在其 viewDidLoad
中向 View Controller 添加简单文本,请考虑向该 View Controller 的 View 添加具有透明背景的简单 UILabel
。
关于ios - drawAtPoint 不会在 View 中渲染文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19742105/