UITextView带下划线的文本

时间:2014-02-21 07:17:49

标签: ios7 uitextview underline

我有UITextView并希望为所选文本加下划线。 它正在使用此代码

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

但是在基线下有“尾巴”的字母(如q y g p)没有加下划线(截图:http://i.stack.imgur.com/dRrEH.png)。 另外我注意到基线和下划线之间的空间取决于字体。

如何在没有任何断裂/间距的情况下为文本加下划线?

1 个答案:

答案 0 :(得分: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
相关问题