gpt4 book ai didi

ios - 具有背景但行间距的 UITextView/UILabel

转载 作者:可可西里 更新时间:2023-11-01 03:38:38 26 4
gpt4 key购买 nike

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

enter image description here

我尝试使用 NSAttributedString 并将 NSBackgroundColorAttributeName 设置为 blackColor 但它没有 clearColor 空间字里行间。我还尝试将 lineSpacing 设置为 NSMutableParagraphStyle 但样式看起来仍然像一个大黑 block 。

我只需要一个提示……谢谢!

换句话说,不是这样的:

enter image description here

最佳答案

经过一些研究,我找到了满足我需要的最佳解决方案。以下解决方案仅适用于 iOS7+。

首先,我们将其添加到您的 UITextView 子类的 - (void)drawRect:(CGRect)rect

- (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 的行间距:

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

上面的方法只有在你设置了NSLayoutManagerDelegate时才会被调用。您可以在 initinitWithFrameinitWithCode 方法中执行此操作,如下所示:

self.layoutManager.delegate = self;

另外不要忘记在您的 .h 文件中声明您的子类是一个委托(delegate):

@interface YOUR_SUBCLASS_OF_UITEXTVIEW : UITextView <NSLayoutManagerDelegate>

关于ios - 具有背景但行间距的 UITextView/UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27360006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com