Подтвердить что ты не робот

Iphone UITextView устанавливает межстрочный интервал

Как увеличить пространство в UITextView, чтобы оно выглядело как приложение "Заметки" в iPhone?

4b9b3361

Ответ 1

Ну, теперь на iOS6 существует возможность использования NSParagraphStyle, но она очень плохо документирована и, похоже, работает редко.

im в настоящее время работает над этим следующим образом:

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];

Проблема в том, что при установке шрифта высота строки перестает работать. Очень странно, пока не найдено исправления.

Также вы можете создать настраиваемое представление Attributed CoreText... но его немного больше технического, вы можете найти демонстрацию того, как это делается здесь

Я надеюсь, что что-то поможет.

Ответ 2

Чтобы изменить интервал между строками:

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;

Ответ 3

Посмотрите на документацию для UITextView достаточно, чтобы определить, что изменение межстрочного интервала не поддерживается этим элементом управления.

Для iOS 6 и выше:

Существует возможность, используя 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];

Ответ 4

Для 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)

Ответ 5

В нескольких ответах выше атрибут lineHeightMultiple используется неправильно:

paragraphStyle.lineHeightMultiple = 50.0f;

В соответствии с официальной документацией lineHeightMultiple является множителем, а не абсолютной высотой строки:

Естественная высота линии приемника умножается на этот фактор (если положительный), прежде чем ограничиться минимумом и максимальная высота линии. Значение по умолчанию этого значения равно 0.0. https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/ApplicationKit/Classes/NSParagraphStyle_Class/index.html#//apple_ref/occ/instp/NSParagraphStyle/maximumLineHeight

Таким образом, код ниже:

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

эквивалентно

paragraphStyle.lineHeight = 50.0f

Ответ 6

Если конечным результатом является увеличение межстрочного интервала, вы можете сделать это непосредственно в построителе интерфейса. Установите для свойства Text значение "Attributed", а затем щелкните... справа. Установка свойства Spacing должна правильно обновлять интервал между строками.

Ответ 7

 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];

Ответ 8

С Swift 4 и iOS 11 в соответствии с вашими потребностями вы можете выбрать одну из 3 следующих реализаций, чтобы решить вашу проблему.


# 1. Использование свойств String и UIFontDescriptorSymbolicTraits traitLooseLeading

traitLooseLeading имеет следующее объявление:

Шрифт использует более слабые ведущие значения.

static var traitLooseLeading: UIFontDescriptorSymbolicTraits { get }

В следующем коде показано, как реализовать 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. Использование свойств NSAttributedString и NSMutableParagraphStyle lineSpacing

lineSpacing имеет следующее объявление:

Расстояние в точках между нижней частью одного фрагмента линии и верхней частью следующей.

var lineSpacing: CGFloat { get set }

В следующем коде показано, как реализовать 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. Используя метод String и NSLayoutManagerDelegate protocol layoutManager(_:lineSpacingAfterGlyphAt:withProposedLineFragmentRect:)

layoutManager(_:lineSpacingAfterGlyphAt:withProposedLineFragmentRect:) имеет следующее объявление:

Возвращает интервал после строки, заканчивающейся указанным индексом глифа. [...] Это сообщение отправляется, когда каждая строка выложена, чтобы позволить делегату менеджера компоновки настраивать форму строки.

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

В следующем коде показано, как реализовать 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
    }

}

В качестве альтернативы предыдущему коду, следующий код показывает, как реализовать 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
    }

}