ios - drawAtPoint 不会在 View 中渲染文本

标签 ios objective-c nsstring ios7

我正在尝试使用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 没有被调用,是因为我必须自己调用它吗?我认为这个方法应该在初始化时调用,而不必我调用它。

最佳答案

您需要引用当前图形上下文才能使用此函数:docsviewDidLoad: 中没有此引用。通常这是在drawRect:内完成的。有多种方法可以在生成屏幕外内容时使用它 - 但这似乎不符合您的需求。

如果您想在其 viewDidLoad 中向 View Controller 添加简单文本,请考虑向该 View Controller 的 View 添加具有透明背景的简单 UILabel

关于ios - drawAtPoint 不会在 View 中渲染文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19742105/

相关文章:

ios - 如何以一般形式表示 nsstring 以进行搜索或比较?

iphone - 没有引用目标 View 时如何设置动画?

ios - 使用 UISwitch 从数组中删除对象

ios - UISearchBar 范围栏位置?

iphone - 更改 UITextView 中所选单词/行的字体格式

ios - UITableView 单元自动调整一些由 AFNetworking 2.0 提供的 ImageView

objective-c - 检测 iOS 8 自定义键盘中的键盘类型更改

c++ - 使用 c++ std::unique_ptr<> 或 std::shared_ptr<> 管理 objective-C 对象

objective-c - NSString 比较 :options:range: - which value to pass for no options?

objective-c - stringByTrimmingCharactersInSet : is not removing characters in the middle of the string