UITextView / UILabel有背景但行之间有间距 [英] UITextView/UILabel with background but with spacing between lines

查看:311
本文介绍了UITextView / UILabel有背景但行之间有间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在iOS中实现这种风格?

How can I achieve this kind of style in iOS?

我尝试使用 NSAttributedString 并设置 NSBackgroundColorAttributeName as blackColor 但是它们之间没有 clearColor 空格。我还尝试将 lineSpacing 设置为 NSMutableParagraphStyle 但是,样式看起来像是一个大黑块。

I tried using NSAttributedString and setting NSBackgroundColorAttributeName as blackColor but then it doesn't have a clearColor space between the lines. I also tried to set a lineSpacing to the NSMutableParagraphStyle but still, the style looks like one big black block.

我只需要提示以哪种方式去...谢谢!

I just need a hint in which way to go... thanks!

换句话说,不是像这个:

In other words, not something like this:

推荐答案

经过一番研究,我发现了我需要的最佳解决方案。
下面的解决方案只有iOS7 +。

After some research I found the best solution for what I needed. The solution below is only iOS7+.

首先我们将此添加到 - (void)drawRect:(CGRect)rect 你的 UITextView 子类。

First we add this to - (void)drawRect:(CGRect)rect of your UITextView subclass.

- (void)drawRect:(CGRect)rect    

    /// Position each line behind each line.
    [self.layoutManager enumerateLineFragmentsForGlyphRange:NSMakeRange(0, self.text.length) usingBlock:^(CGRect rect, CGRect usedRect, NSTextContainer *textContainer, NSRange glyphRange, BOOL *stop) {

        /// The frame of the rectangle.
        UIBezierPath *rectanglePath = [UIBezierPath bezierPathWithRect:CGRectMake(usedRect.origin.x, usedRect.origin.y+3, usedRect.size.width, usedRect.size.height-4)];

        /// Set the background color for each line.
        [UIColor.blackColor setFill];

        /// Build the rectangle.
        [rectanglePath fill];
    }];
 }];

然后我们设置UITextView的行间距:

Then we set the line spacing for the UITextView:

- (CGFloat)layoutManager:(NSLayoutManager *)layoutManager lineSpacingAfterGlyphAtIndex:(NSUInteger)glyphIndex withProposedLineFragmentRect:(CGRect)rect
{
    return 15;
}

只有在设置时才调用上述方法NSLayoutManagerDelegate 。您可以在 init initWithFrame initWithCode 中执行此操作这样的方法:

The method above is only called if you set the NSLayoutManagerDelegate. You could do that in your init, initWithFrame and initWithCode methods like this:

self.layoutManager.delegate = self;

另外,请不要忘记声明您的子类是中的委托.h file:

Also don't forget to declare that your subclass is a delegate in your .h file:

@interface YOUR_SUBCLASS_OF_UITEXTVIEW : UITextView <NSLayoutManagerDelegate>

这篇关于UITextView / UILabel有背景但行之间有间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆