0

How can I insert a line break before a new line starts in a UITextView? Images below should shed more light.
Orginal
original Final Outcome
final

Community
  • 1
  • 1
kye
  • 2,166
  • 3
  • 27
  • 41
  • have you tried `\n` ? Or do you mean line-spacing? – R Menke Nov 02 '15 at 02:04
  • [line-spacing swift](http://stackoverflow.com/questions/25348766/swift-adjusting-the-line-height-of-uitextview) – R Menke Nov 02 '15 at 02:06
  • @RMenke only first line is effected using "\n". I didnt mean line-spacing, sorry. – kye Nov 02 '15 at 02:09
  • either use `\n` at the end of each line, or set the line-spacing to be the same height as a line break. No other options. I would set the line-spacing. Calculating when a new line starts and inserting `\n` is not impossible but a whole lot more work and "slow". – R Menke Nov 02 '15 at 02:11
  • Im not too sure how `\n` at the end of each will work since line breaks are dictated by the width of the UITextVIew. Also would setting the line-spacing to be the same height as a line break create a new line? or just create a spacing between the lines. – kye Nov 02 '15 at 02:19
  • Why do you need the line-break? I assumed that is was for visual effect. – R Menke Nov 02 '15 at 02:23
  • @RMenke It's to easy editing after text has been set in UITextView. Edited text will be presented on top of original text – kye Nov 02 '15 at 02:32

3 Answers3

1

If you want to display text from two sources but with the text appearing in one view where lines from each source alternate you could create a class like in the example below.

I created a subclass of UIView which comes with two UITextViews as Subviews. Texts are set through the DoubleTextView class.

The UITextViews have a difference in origin so text will appear to alternate lines.


Benefits:

  • Don't worry about which text is original and which text you added programmatically.
  • Easy to set different styles

Possible downside:

  • Only one UITextView will be editable, since one will always be untouchable ( it is covered )

Result:

enter image description here

Some better maths are needed to position or space the text ideally.


Code:

Convert string to NSMutableAttributedString and set line-spacing:

func convertLineHeight(string string_I: String) -> NSMutableAttributedString {

    let style = NSMutableParagraphStyle()
    style.lineSpacing = lineSpacing + self.font.lineHeight
    let attributes = [NSParagraphStyleAttributeName : style]
    let attributedString =  NSMutableAttributedString(string: string_I, attributes:attributes)

    return attributedString

}

Offset one view:

let alphaPoint = CGPoint(x: 0, y: (lineSpacing / 2) + self.font.lineHeight)
// this is almost perfect. is off by a few pixels.

Full class:

class DoubleTextView : UIView {

    private var alphaTextView : UITextView!
    private var betaTextView : UITextView!

    private var lineSpacing : CGFloat = 0

    var font : UIFont = UIFont.systemFontOfSize(UIFont.systemFontSize()) {
        didSet {
            alphaTextView.font = self.font
            betaTextView.font = self.font
        }
    }

    var alphaText : String = "" {
        didSet {
            alphaTextView.attributedText = convertLineHeight(string: alphaText)
        }
    }
    var betaText : String = "" {
        didSet {
            betaTextView.attributedText = convertLineHeight(string: betaText)
        }
    }

    var alphaAttributedText : NSMutableAttributedString = NSMutableAttributedString() {
        didSet {
            alphaTextView.attributedText = convertLineHeight(attributedString: alphaAttributedText)
        }
    }

    var betaAttributedText : NSMutableAttributedString = NSMutableAttributedString() {
        didSet {
            betaTextView.attributedText = convertLineHeight(attributedString: betaAttributedText)
        }
    }

    init(frame: CGRect, lineSpacing lineSpacing_I: CGFloat) {

        lineSpacing = lineSpacing_I

        super.init(frame: frame)

        var adjustedSize = frame.size
        adjustedSize.height -= ((lineSpacing / 2) + self.font.lineHeight)

        let alphaPoint = CGPoint(x: 0, y: (lineSpacing / 2) + self.font.lineHeight)

        alphaTextView = UITextView(frame: CGRect(origin: alphaPoint, size: adjustedSize))
        alphaTextView.backgroundColor = UIColor.clearColor()
        alphaTextView.font = self.font
        betaTextView = UITextView(frame: CGRect(origin: CGPointZero, size: adjustedSize))
        betaTextView.font = self.font
        betaTextView.backgroundColor = UIColor.clearColor()



        self.addSubview(alphaTextView)
        self.addSubview(betaTextView)
    }

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


    private func convertLineHeight(string string_I: String) -> NSMutableAttributedString {

        let style = NSMutableParagraphStyle()
        style.lineSpacing = lineSpacing + self.font.lineHeight
        let attributes = [NSParagraphStyleAttributeName : style]
        let attributedString =  NSMutableAttributedString(string: string_I, attributes:attributes)

        return attributedString

    }

    private func convertLineHeight(attributedString attributedString_I: NSMutableAttributedString) -> NSMutableAttributedString {

        let style = NSMutableParagraphStyle()
        style.lineSpacing = lineSpacing + self.font.lineHeight
        let attributes = [NSParagraphStyleAttributeName : style]
        attributedString_I.addAttributes(attributes, range: (attributedString_I.string as NSString).rangeOfString(attributedString_I.string))
        return attributedString_I

    }


}


var test = DoubleTextView(frame: CGRect(x: 0, y: 0, width: 200, height: 400), lineSpacing: 20)
test.backgroundColor = UIColor.whiteColor()

test.alphaText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

test.betaText = "This is the second text. It shows comments, edits, suggestions, thoughts about the first"
R Menke
  • 8,183
  • 4
  • 35
  • 63
0

Not sure this is the best solution but it works for now. (Very open to other answers). Thanks to RMenke for the idea

    let outputString = "";
    let splitInput = [String]()
    let input = incomingText
    outPut =  input.componentsSeparatedByCharactersInSet(.newlineCharacterSet())
    for index in splitInput{
   self.outputString +=  index + "\n\n"   
   }
   print(outputString)
Community
  • 1
  • 1
kye
  • 2,166
  • 3
  • 27
  • 41
-5
txtField.text = textField.text.stringByAppendingString("\n")

answer/idea from chrissukhram

stumped
  • 3,235
  • 7
  • 43
  • 76
  • Please explain, what the core issue is, what has been done to resolve it, and why. As currently written, this answer is not very useful. – IInspectable Jan 18 '16 at 23:50