我想在我的UITextView中绘制线条。经过一番研究后我发现了这个:
UITextView ruled line background but wrong line height
我在我的代码中尝试过,调用了drawRect但是没有绘制线条。有人可以帮助我吗?
#import "FacebookViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface MyViewController (){
UITextView *text;
}
@end
@implementation MyViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Do any additionnal customisation
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
text.contentMode = UIViewContentModeRedraw;
//TextView init
text = [[UITextView alloc]initWithFrame:CGRectMake(0,44,320,380)];
[self.view addSubview:text];
text.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)drawRect:(CGRect)rect {
NSLog(@"TEST");
//Get the current drawing context
CGContextRef context = UIGraphicsGetCurrentContext();
//Set the line color and width
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 1.0f);
//Start a new Path
CGContextBeginPath(context);
//Find the number of lines in our textView + add a bit more height to draw lines in the empty part of the view
NSUInteger numberOfLines = (text.contentSize.height + text.bounds.size.height) / text.font.leading;
//Set the line offset from the baseline. (I'm sure there's a concrete way to calculate this.)
CGFloat baselineOffset = 6.0f;
//iterate over numberOfLines and draw each line
for (int x = 0; x < numberOfLines; x++) {
//0.5f offset lines up line with pixel boundary
CGContextMoveToPoint(context, text.bounds.origin.x, text.font.leading*x + 0.5f + baselineOffset);
CGContextAddLineToPoint(context, text.bounds.size.width, text.font.leading*x + 0.5f + baselineOffset);
}
CGContextClosePath(context);
CGContextStrokePath(context);
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[text setNeedsDisplay];
}
@end
可能是一个愚蠢的错误,但我找不到它
由于
答案 0 :(得分:1)
当我看着你的代码时,一切都很好。也许有颜色的东西?可能与背景颜色相同或类似。
可能忘了设置内容模式:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.contentMode = UIViewContentModeRedraw;
}
return self;
}
修改强>
我想我知道:
您在显示后忘记设置[myTextView setNeedsDisplay];
。 Read here
修改强>
首先创建视图:
t = [[[MyTextView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)] autorelease];
[self.view addSubview:t];
t.delegate = self;
使你的viewcontroller实现UITextViewDelegate
并在那之后
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[t setNeedsDisplay];
}
这应该有效
答案 1 :(得分:1)
我有同样的问题.. 我认为你不是UITextView的子类
由于UIViewController没有实现此方法,只有UITextView执行
所以只需将其子类化..您的代码将起作用
答案 2 :(得分:0)
您是否有可能成功绘制但是被匹配的背景颜色遮挡了?我注意到你选择的颜色的alpha非常小。如果只是为了排除这一点,请更改:
CGContextSetStrokeColorWithColor(context, [UIColor colorWithWhite:0.5f alpha:0.15f].CGColor);
到
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);