ios iphone UITextView 设置行间距

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4277551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:09:07  来源:igfitidea点击:

iphone UITextView set line spacing

iosiphoneuitextview

提问by Satyam

How can I increase line space in UITextView so that it looks like "Notes" app in iPhone?

如何增加 UITextView 中的行距,使其看起来像 iPhone 中的“Notes”应用程序?

回答by Bernardo Del Castillo Suarez

Well now on iOS6, there is a possibility, using NSParagraphStyle, but it is very poorly documented and seems to work seldomly.

那么现在在 iOS6 上,有可能使用NSParagraphStyle,但它的文档很差,似乎很少工作。

I'm currently working about it like this:

我目前正在这样做:

UITextView *lab = [LocalTexts objectAtIndex:j];

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineHeightMultiple = 50.0f;
paragraphStyle.maximumLineHeight = 50.0f;
paragraphStyle.minimumLineHeight = 50.0f;

NSString *string = lab.text;
NSDictionary *ats = @{
    NSFontAttributeName: [UIFont fontWithName:@"DIN Medium" size:16.0f],
    NSParagraphStyleAttributeName: paragraphStyle, 
};

lab.attributedText = [[NSAttributedString alloc] initWithString:string attributes:ats];

Problem is that when you set the Font, the line height stops working. Very odd. I haven't found a fix for it yet.

问题是当您设置字体时,行高停止工作。很奇怪。我还没有找到解决办法。

Also you can create a custom Attributed CoreText view... but it's a bit more technical, you can find a demo of how it is done here

你也可以创建一个自定义的 Attributed CoreText 视图......但它更具技术性,你可以在这里找到它是如何完成的演示

Well I hope something helps.

好吧,我希望有所帮助。

回答by Imanou Petit

With Swift 4 and iOS 11, according to your needs, you can choose one of the 3 following implementationsin order to solve your problem.

使用 Swift 4 和 iOS 11,您可以根据需要,选择以下 3 种实现之一来解决您的问题。



#1. Using Stringand UIFontDescriptorSymbolicTraitstraitLooseLeadingproperty

#1. 使用StringUIFontDescriptorSymbolicTraitstraitLooseLeading财产

traitLooseLeadinghas the following declaration:

traitLooseLeading有以下声明:

The font uses looser leading values.

字体使用较宽松的前导值。

static var traitLooseLeading: UIFontDescriptorSymbolicTraits { get }

The following code shows how to implement traitLooseLeadingin order to have a looser font leading for your UItextView.

以下代码显示了如何实施traitLooseLeading以便为您的UItextView.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let textView = UITextView()
        view.addSubview(textView)

        textView.text = """
        Lorem ipsum
        Dolor sit amet,
        consectetur adipiscing elit
        """

        if let fontDescriptor = UIFontDescriptor
            .preferredFontDescriptor(withTextStyle: UIFontTextStyle.body)
            .withSymbolicTraits(UIFontDescriptorSymbolicTraits.traitLooseLeading) {
            let looseLeadingFont = UIFont(descriptor: fontDescriptor, size: 0)
            textView.font = looseLeadingFont
        }

        // Layout textView
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.topAnchor.constraint(equalTo: view.readableContentGuide.topAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: view.readableContentGuide.bottomAnchor).isActive = true
        textView.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor).isActive = true
    }

}


#2. Using NSAttributedStringand NSMutableParagraphStylelineSpacingproperty

#2. 使用NSAttributedStringNSMutableParagraphStylelineSpacing财产

lineSpacinghas the following declaration:

lineSpacing有以下声明:

The distance in points between the bottom of one line fragment and the top of the next.

一个线条片段的底部和下一个片段的顶部之间的距离(以磅为单位)。

var lineSpacing: CGFloat { get set }

The following code shows how to implement lineSpacingin order to have a specific line spacing for some attributed text in your UItextView.

以下代码显示了如何实施lineSpacing以便为UItextView.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let string = """
        Lorem ipsum
        Dolor sit amet,
        consectetur adipiscing elit
        """

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 15

        let attributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.paragraphStyle: paragraphStyle]
        let attributedString = NSAttributedString(string: string, attributes: attributes)

        let textView = UITextView()
        textView.attributedText = attributedString
        view.addSubview(textView)

        // Layout textView
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.topAnchor.constraint(equalTo: view.readableContentGuide.topAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: view.readableContentGuide.bottomAnchor).isActive = true
        textView.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor).isActive = true
    }

}


#3. Using Stringand NSLayoutManagerDelegateprotocol layoutManager(_:lineSpacingAfterGlyphAt:withProposedLineFragmentRect:)method

#3. 使用StringNSLayoutManagerDelegate协议layoutManager(_:lineSpacingAfterGlyphAt:withProposedLineFragmentRect:)方法

layoutManager(_:lineSpacingAfterGlyphAt:withProposedLineFragmentRect:)has the following declaration:

layoutManager(_:lineSpacingAfterGlyphAt:withProposedLineFragmentRect:)有以下声明:

Returns the spacing after the line ending with the given glyph index. [...] This message is sent while each line is laid out to enable the layout manager delegate to customize the shape of line.

返回以给定字形索引结尾的行之后的间距。[...],同时每行被布置,以使布局管理器代理定制线的形状发送此消息。

optional func layoutManager(_ layoutManager: NSLayoutManager, lineSpacingAfterGlyphAt glyphIndex: Int, withProposedLineFragmentRect rect: CGRect) -> CGFloat

The following code shows how to implement layoutManager(_:lineSpacingAfterGlyphAt:withProposedLineFragmentRect:)in order to have a specific line spacing for your UItextView.

以下代码显示了如何实施layoutManager(_:lineSpacingAfterGlyphAt:withProposedLineFragmentRect:)以便为您的UItextView.

import UIKit

class ViewController: UIViewController, NSLayoutManagerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let textView = UITextView()
        textView.layoutManager.delegate = self
        view.addSubview(textView)

        textView.text = """
        Lorem ipsum
        Dolor sit amet,
        consectetur adipiscing elit
        """

        // Layout textView
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.topAnchor.constraint(equalTo: view.readableContentGuide.topAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: view.readableContentGuide.bottomAnchor).isActive = true
        textView.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor).isActive = true
    }

    // MARK: - NSLayoutManagerDelegate

    func layoutManager(_ layoutManager: NSLayoutManager, lineSpacingAfterGlyphAt glyphIndex: Int, withProposedLineFragmentRect rect: CGRect) -> CGFloat {
        return 15
    }

}

As an alternative to the previous code, the following code shows how to implement layoutManager(_:lineSpacingAfterGlyphAt:withProposedLineFragmentRect:)in a UITextViewsubclass.

作为前面代码的替代,下面的代码展示了如何layoutManager(_:lineSpacingAfterGlyphAt:withProposedLineFragmentRect:)UITextView子类中实现。

import UIKit

class LineSpacingTextView: UITextView, NSLayoutManagerDelegate {

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        layoutManager.delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - NSLayoutManagerDelegate

    func layoutManager(_ layoutManager: NSLayoutManager, lineSpacingAfterGlyphAt glyphIndex: Int, withProposedLineFragmentRect rect: CGRect) -> CGFloat {
        return 15
    }

}
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let textView = LineSpacingTextView()
        view.addSubview(textView)

        textView.text = """
        Lorem ipsum
        Dolor sit amet,
        consectetur adipiscing elit
        """

        // Layout textView
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.topAnchor.constraint(equalTo: view.readableContentGuide.topAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: view.readableContentGuide.bottomAnchor).isActive = true
        textView.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor).isActive = true
    }

}

回答by sash

To change line spacing:

要更改行距:

NSString *textViewText =self.myTextView.text;

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:textViewText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 30;
NSDictionary *dict = @{NSParagraphStyleAttributeName : paragraphStyle };
[attributedString addAttributes:dict range:NSMakeRange(0, [textViewText length])];

self.myTextView.attributedText = attributedString;

回答by KingofBliss

A look at the documentation for UITextView is sufficient to determine that changing the line spacing is not supported by that control.

查看 UITextView 的文档足以确定该控件不支持更改行间距。

For iOS 6 and above:

对于 iOS 6 及更高版本:

There is a possibility, using NSParagraphStyle,

有一种可能性,使用 NSParagraphStyle,

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineHeightMultiple = 50.0f;
paragraphStyle.maximumLineHeight = 50.0f;
paragraphStyle.minimumLineHeight = 50.0f;
NSString *string = @"your paragraph here";
NSDictionary *attribute = @{
   NSParagraphStyleAttributeName : paragraphStyle, 
   };
[textview setFont:[uifont fontwithname:@"Arial" size:20.0f]];
textview.attributedText = [[NSAttributedString alloc] initWithString:string attributes:attribute];

回答by swiftBoy

For Swift 2.2

对于Swift 2.2

let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = 20.0
paragraphStyle.maximumLineHeight = 20.0
paragraphStyle.minimumLineHeight = 20.0
let ats = [NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 11.0)!, NSParagraphStyleAttributeName: paragraphStyle]
cell.textView.attributedText = NSAttributedString(string: "you string here", attributes: ats)

回答by mcfroob

If the end result is to increase line spacing, you can do it directly in interface builder. Set the Text property to "Attributed" and then click the ... on the right. Setting the Spacing property there should update your line spacing correctly.

如果最终结果是增加行距,您可以直接在界面构建器中进行。将 Text 属性设置为“Attributed”,然后单击右侧的 ...。在那里设置 Spacing 属性应该正确更新您的行距。

回答by Yuri Vorontsov

In several answers above attribute lineHeightMultipleis misused:

在上面的几个答案中,属性lineHeightMultiple被滥用:

paragraphStyle.lineHeightMultiple = 50.0f;

Following to the official documentation lineHeightMultipleis an multiplier and not an absolute height of a string:

以下官方文档lineHeightMultiple是一个乘数而不是字符串的绝对高度:

The natural line height of the receiver is multiplied by this factor (if positive) before being constrained by minimum and maximum line height. The default value of this property is 0.0. https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/ApplicationKit/Classes/NSParagraphStyle_Class/index.html#//apple_ref/occ/instp/NSParagraphStyle/maximumLineHeight

在受最小和最大行高约束之前,接收器的自然行高乘以该因子(如果为正)。此属性的默认值为 0.0。 https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/ApplicationKit/Classes/NSParagraphStyle_Class/index.html#//apple_ref/occ/instp/NSParagraphStyle/maximumLineHeight

Thereby, the code below:

因此,下面的代码:

paragraphStyle.lineHeightMultiple = 50.0f;
paragraphStyle.maximumLineHeight = 50.0f;
paragraphStyle.minimumLineHeight = 50.0f;

is equivalent to

相当于

paragraphStyle.lineHeight = 50.0f

回答by kshitij godara

 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
   paragraphStyle.lineHeightMultiple = 50.0f;
   paragraphStyle.maximumLineHeight = 50.0f;
   paragraphStyle.minimumLineHeight = 50.0f;
     NSString *string = @"if you want reduce or increase space between lines in uitextview ,you can do this with this,but donot set font on this paragraph , set this on uitextveiw.";

    NSDictionary *ats = @{
   NSParagraphStyleAttributeName : paragraphStyle, 
     };

    [textview setFont:[uifont fontwithname:@"Arial" size:20.0f]];
    textview.attributedText = [[NSAttributedString alloc] initWithString:string attributes:ats];