Search code examples
iosswifttextsharesample

Swift: How to show sample code as a text or a text field in my app?


Is it possible to get the multiline code sample as a text with the possibility to share it later? Let say I have a sample code:

    let a = SKSpriteNode(imageNamed: "ball01")
    a.position = CGPoint(x: width*0.5, y: height*0.5)
    a.size = CGSize(width: width*0.1, height: width*0.1)
    a.physicsBody = SKPhysicsBody(circleOfRadius: a.frame.width*0.5)

Is it possible to share it as a multiline text? I found some discussions about html, but nothing about the "normal" swift code. Thank you.

Here is a desired sample which could be shared as a Note or smth like that: enter image description here


Solution

  • Find simple and elegant solution here: How to work with Multi-Line String Literals in Swift:

    let multilineString: """
          let a = SKSpriteNode(imageNamed: "ball01")
          a.position = CGPoint(x: width*0.5, y: height*0.5)
          a.size = CGSize(width: width*0.1, height: width*0.1)
          a.physicsBody = SKPhysicsBody(circleOfRadius: a.frame.width*0.5)
          """
    
          label.text = multilineString
          label.numberOfLines = 0