2017-09-11 1 views
0

CoreText에 익숙해지기 위해 필자는 노트 작성 응용 프로그램을 작성하기 시작했습니다.UITextView 내에서 블록 인용 부호와 같은 텍스트 형식을 지정하는 방법

AttributedStrings과 함께 정규 표현식을 사용하고 있으며 지금 입력하고있는 StackOverflow 텍스트 상자의 기능을 본질적으로 모방하려고합니다.

굵은

이탤릭체

헤더

emphasis blocks

하지만 블록 견적을 만들기 위해 고군분투 :

내가 좋아하는 일반적인 것들 모두가/코드 블록.

텍스트가 아무리 길어도 가장자리로 이동하는 상자를 만들거나 자체 줄 바꿈하는 경우와 같은 부분입니다.

And it changes the background color 

이 AttributedStrings을 사용하여 엄격 할 경우에도 수 있습니까? 나는 HTML/CSS가 주입 된 몇 가지 오래된 예제를 보았습니다.하지만 특별한 NSAttributedStringKey 조합을 사용하여이를 수행 할 수 있기를 희망했습니다.

답변

1

예, 가능합니다. 여기

import UIKit 
import PlaygroundSupport 

let richText = NSMutableAttributedString() 

let chunk0 = NSAttributedString(string: "But I am struggling to make a block quote/code block.\n\n") 
richText.append(chunk0) 

let paragraphStyle = NSMutableParagraphStyle() 
paragraphStyle.headIndent = 20 
// Note that setting paragraphStyle.firstLineHeadIndent 
// doesn't use the background color for the first line's 
// indentation. Use a tab stop on the first line instead. 
paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: paragraphStyle.headIndent, options: [:])] 

let chunk1 = NSAttributedString(string: "\tSomething like this where it breaks to its own line and creates a box that goes to the edge no matter how long the text is.\n", attributes: [ 
    NSParagraphStyleAttributeName: paragraphStyle, 
    NSBackgroundColorAttributeName: UIColor.yellow 
]) 
richText.append(chunk1) 

let chunk2 = NSAttributedString(string: "\nIs this even possible to do strictly using AttributedStrings?") 
richText.append(chunk2) 

let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 120, height: 400)) 
textView.backgroundColor = .white 
textView.attributedText = richText 
PlaygroundPage.current.liveView = textView 

출력 것 : 여기 스위프트 3 샘플 놀이터입니다

result

그러나 UITextView 웹보다는 (레이아웃과 스타일에 대한) 훨씬 덜 강력한 것을 명심하는 것이 중요합니다 전망. (stackoverflow가 blockquote 상자의 왼쪽 가장자리를 따라 더 어두운 색 선을 사용하는 것처럼) 멋지게하려면 HTML과 CSS를 생성하고 웹보기를 사용해야합니다.

+0

아, 그게 단락 스타일을 사용하는 방법입니다 :) 감사합니다! 또한 옵션 : [:] 나는 전적으로 생각하지 않았지만 도움이 될 것으로 나타났습니다. 그래서 두 번 감사드립니다! – sargturner

관련 문제