Fab*_*bio 6 cocoa-touch uikit ios
我怎样才能在iOS中实现这种风格?
我尝试使用NSAttributedString
和设置NSBackgroundColorAttributeName
为,blackColor
但它没有clearColor
行之间的空格.我也试着设置lineSpacing
为NSMutableParagraphStyle
,但仍然,样式看起来像一个大黑块.
我只需要一个提示,以哪种方式去...谢谢!
换句话说,不是这样的:
经过一些研究,我发现了我需要的最佳解决方案.以下解决方案仅限iOS7 +.
首先,我们将这个添加到- (void)drawRect:(CGRect)rect
您的UITextView
子类中.
- (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];
}];
}];
Run Code Online (Sandbox Code Playgroud)
然后我们设置UITextView的行间距:
- (CGFloat)layoutManager:(NSLayoutManager *)layoutManager lineSpacingAfterGlyphAtIndex:(NSUInteger)glyphIndex withProposedLineFragmentRect:(CGRect)rect
{
return 15;
}
Run Code Online (Sandbox Code Playgroud)
只有在设置时才会调用上面的方法NSLayoutManagerDelegate
.你可以这样做,在你的init
,initWithFrame
而initWithCode
方法是这样的:
self.layoutManager.delegate = self;
Run Code Online (Sandbox Code Playgroud)
另外,不要忘记声明您的子类是.h
文件中的委托:
@interface YOUR_SUBCLASS_OF_UITEXTVIEW : UITextView <NSLayoutManagerDelegate>
Run Code Online (Sandbox Code Playgroud)
@Fabio解决方案的Swift 3 版本:
class splitedTextView: UITextView, NSLayoutManagerDelegate {
override func awakeFromNib() {
self.layoutManager.delegate = self
}
override func draw(_ rect: CGRect) {
self.layoutManager.enumerateLineFragments(forGlyphRange: NSMakeRange(0, self.text.characters.count)) { (rect, usedRect, textContainer, glyphRange, Bool) in
let rectanglePath = UIBezierPath(rect: CGRect(x: usedRect.origin.x, y: usedRect.origin.y+3, width: usedRect.size.width, height: usedRect.size.height-4))
UIColor.black.setFill()
rectanglePath.fill()
}
}
func layoutManager(_ layoutManager: NSLayoutManager, lineSpacingAfterGlyphAt glyphIndex: Int, withProposedLineFragmentRect rect: CGRect) -> CGFloat {
return 15
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以在textView
子类中创建一个变量来管理矩形的颜色:
var color: UIColor?
Run Code Online (Sandbox Code Playgroud)
然后在您的textView
子类中使用它而不是默认黑色:
self.color?.setFill()
Run Code Online (Sandbox Code Playgroud)
此外,如果您这样做,请不要忘记使用setNeedsDisplay()
重绘textView
和应用您的自定义颜色。
归档时间: |
|
查看次数: |
2896 次 |
最近记录: |