2014-02-21 66 views
1

我有UITextView并且想要下划线选定的文本。 它是由该代码UITextView带下划线的文本

NSRange range = selectedTextView.selectedRange; 
NSTextStorage *textStorage = selectedTextView.textStorage; 
[textStorage addAttribute: NSUnderlineStyleAttributeName 
        value:[NSNumber numberWithInt:NSUnderlineStyleSingle] 
        range:range]; 

但其中有“尾部”下基线(为qÝ克对)的字母不加下划线工作(截图:http://i.stack.imgur.com/dRrEH.png)。 另外我注意到基线和下划线之间的空间取决于字体。

如何在没有任何折线/间距的情况下强调文本?

回答

0
#import <UIKit/UIKit.h> 

@interface TextViewWithUnderline : UITextView 

@end 

#import "TextViewWithUnderline.h" 

@implementation TextViewWithUnderline 

- (id)initWithFrame:(CGRect)frame { 

    self = [super initWithFrame:frame]; 
    if (self) { 
     //self.contentMode = UIViewContentModeRedraw; 
    } 
    return self; 
} 

- (void)drawRect:(CGRect)rect { 

    //Get the current drawing context 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    //Set the line color and width 
    CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].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 = (self.contentSize.height + self.bounds.size.height)/self.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 = 1; x < numberOfLines; x++) { 
     //0.5f offset lines up line with pixel boundary 
     CGContextMoveToPoint(context, self.bounds.origin.x + 10, self.font.leading*x + 0.5f + baselineOffset); 
     CGContextAddLineToPoint(context, self.bounds.size.width - 10, self.font.leading*x + 0.5f + baselineOffset); 
    } 

    //Close our Path and Stroke (draw) it 
    CGContextClosePath(context); 
    CGContextStrokePath(context); 
} 

@end 

#import <UIKit/UIKit.h> 
#import "TextViewWithUnderline.h" 
@interface CustomTextView : UIViewController 
@property (weak, nonatomic) IBOutlet TextViewWithUnderline *textView; 

@end 

#import "CustomTextView.h" 

@interface CustomTextView() 

@end 

@implementation CustomTextView 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view. 
    self.textView.contentMode = UIViewContentModeRedraw; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

@end