2017-01-31 1 views
1

UITextView가 포함 된보기 컨트롤러가 있습니다. 이 UITextView는 텍스트를 제어하는 ​​데이터 모델 (약 30 개의 다른 텍스트 옵션)에 따라 프로그래밍 방식으로 텍스트를 업데이트합니다. UITextView의 내용은 항상 길이가 약 450 단어가됩니다. 단락의 범위는 2 - 5입니다.단락 표제를 프로그래밍 방식으로 UITextView에 추가하기

모든 것이 완벽합니다. 단락을 깨기위한 시각적 인 방법이 필요합니다. 지금은 \ n \ n 단락 사이에 몇 줄 바꿈을 사용하고 있습니다. 이 방법이 작동하는 동안 궁극적으로 표제가 필요합니다.

IB에서 텍스트 속성을 일반에서 속성으로 변경했습니다. 이렇게하면 Xcode에서 WYSIWYG와 같은 방식으로 텍스트를 수정할 수 있습니다. 훌륭하게 작동하지만 IB를 사용하여 텍스트를 변경하지 않습니다.

WebView (아래 코드)를 사용해 보았습니다. H1과 P 태그가있는 매우 기본적인 HTML 파일을 만들었습니다. 불행히도 내 프로젝트에서 30 + HTML 파일을 만듭니다. 나는 관리의 관점에서 이것을 좋아하지 않는다. 텍스트는 또한 웹보기로 인 선택이 될 수 없다 (나는이 문제를 완화하기 위해 CSS [-webkit-사용자 선택]에 의존하지 않습니다.)

let path: String? = Bundle.main.path(forResource: "myHTML", ofType: "html") 
    let file = try? String(contentsOfFile: path!, encoding: String.Encoding.utf8) 
    let baseURL = URL(fileURLWithPath: Bundle.main.bundlePath) 
    self.myWebView.loadHTMLString(file!, baseURL: baseURL) 

내 이상적인 솔루션

현재 설정을 적용해도됩니까? 프로그래밍 방식으로 내 데이터 모델로 UITextView 텍스트를 변경하면서 코드의 텍스트 특성을 변경하여 단락 제목을 만들 수 있습니까?

This is my current UI without any attributed text This is my ultimate end-goal

편집 -이 MVC

allFormattedDescriptions: [ 
Formatted(heading: "heading 1", descriptionText: "Lorem Ipsum Paragraph 1"), 
Formatted(heading: "heading 2", descriptionText: "Lorem Ipsum Paragraph 2"), 
Formatted(heading: "heading 3", descriptionText: "Lorem Ipsum Paragraph 3") 
] 
// Ideal formatting; every paragraph will have a heading. Can handle that with one object that requires both a heading and description text (paragraph). 

struct Formatted { 

var heading: String! 
var descriptionText: String! 

var bodyParagraphStyle: NSMutableParagraphStyle = { 
    let style = NSMutableParagraphStyle() 
    style.lineSpacing = 10 
    style.paragraphSpacingBefore = 6 
    style.paragraphSpacing = 6 
    return style 
}() 

var headerParagraphStyle: NSMutableParagraphStyle = { 
    let style = NSMutableParagraphStyle() 
    style.paragraphSpacingBefore = 24 
    return style 
}() 

var bodyAttributes: [String: AnyObject]! 
var headerAttributes: [String: AnyObject]! 

} 
+0

인가? – AdamPro13

+0

코드에서 확실히 할 수 있습니다. NSMutableAttributedString은 속성을 추가하고 제거 할 수있게합니다. 또한 HTML을 표시하는 데 사용할 수 있습니다. HTML을 표시 할 필요가 없다면'enumerateAttributesInRange'를 호출하여 모든 속성을 가져 와서 수정하거나'addAttributes' 또는'setAttributes'를 호출하여 다양한 스타일을 설정할 수 있습니다. 여기에는 단락 스타일 및 들여 쓰기, 줄 간격, 색상, 밑줄, 취소 선, 글꼴 등이 포함됩니다. – Brandon

+0

원하는 것을 얻지 못합니다. 실물 모형을 제공 할 수 있습니까? –

답변

3

사용 NS(Mutable)ParagraphStyleNS(Mutable)AttributedString와 함께 작동하도록하려고합니다. 예를 들면 :

class ViewController: UIViewController { 
    @IBOutlet weak var textView: UITextView! 

    var allFormattedDescriptions = [ 
     Formatted(heading: "Introduction to Bacon Ipsum", descriptionText: "Bacon ipsum dolor amet jerky pig pastrami capicola biltong turkey, ball tip fatback andouille porchetta flank swine brisket bacon pork loin. Tongue shank cupim, pastrami spare ribs meatball drumstick pork pork chop. Sirloin flank tenderloin bresaola doner, cupim ribeye drumstick ham hock t-bone pork short ribs shoulder. Fatback ribeye pastrami pancetta, chuck turkey andouille boudin burgdoggen shoulder tongue kielbasa doner shankle turducken. Rump strip steak drumstick, shankle cupim prosciutto jerky bacon doner. Pork chop jowl burgdoggen, cow turkey ball tip doner. Cow ham meatball chuck flank meatloaf prosciutto."), 
     Formatted(heading: "Kielbasa?", descriptionText: "Spare ribs boudin ham leberkas landjaeger filet mignon. Short loin fatback hamburger leberkas chicken. Frankfurter chuck short ribs ball tip, ground round cupim shank brisket venison turducken boudin. Pig sirloin pork loin meatloaf short loin turkey swine.") 
    ] 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let textContent = NSMutableAttributedString() 
     for (index, desc) in allFormattedDescriptions.enumerated() { 
      let includeLinebreak = index < allFormattedDescriptions.count - 1 
      textContent.append(desc.attributeString(includeLineBreak: includeLinebreak)) 
     } 
     textView.attributedText = textContent 
    } 
} 

struct Formatted { 
    var heading: String 
    var descriptionText: String 

    var bodyParagraphStyle: NSMutableParagraphStyle = { 
     let style = NSMutableParagraphStyle() 
     style.lineSpacing = 10 
     style.paragraphSpacingBefore = 6 
     style.paragraphSpacing = 6 
     return style 
    }() 

    var headerParagraphStyle: NSMutableParagraphStyle = { 
     let style = NSMutableParagraphStyle() 
     style.paragraphSpacingBefore = 24 
     return style 
    }() 

    var bodyAttributes: [String: AnyObject] 
    var headerAttributes: [String: AnyObject] 

    func attributeString(includeLineBreak: Bool = true) -> NSAttributedString { 
     let result = NSMutableAttributedString() 
     result.append(NSAttributedString(string: self.heading + "\n", attributes: self.headerAttributes)) 
     result.append(NSAttributedString(string: self.descriptionText, attributes: self.bodyAttributes)) 
     if includeLineBreak { 
      result.append(NSAttributedString(string: "\n", attributes: self.bodyAttributes)) 
     } 

     return result as NSAttributedString 
    } 

    init(heading: String, descriptionText: String) { 
     self.heading = heading 
     self.descriptionText = descriptionText 
     self.bodyAttributes = [ 
      NSFontAttributeName: UIFont(name: "Hoefler Text", size: 14)!, 
      NSParagraphStyleAttributeName: bodyParagraphStyle 
     ] 
     self.headerAttributes = [ 
      NSFontAttributeName: UIFont(name: "Avenir", size: 22)!, 
      NSParagraphStyleAttributeName: headerParagraphStyle, 
      NSForegroundColorAttributeName: UIColor.red 
     ] 
    } 
} 

결과 :

텍스트보기 편집

Formatted text

+1

이것은 매우 좋습니다. 본문과 단락 속성을 분리하는 방법을 좋아합니다. 나는 이것을 MVC로 분해하려고 노력하고 있지만 힘든 시간을 보내고있다. 난 그냥 모델 제목과 단락 텍스트 입력을 처리 할 수 ​​있습니다. 저의 오리지널 포스트에 작은 편집장이있어 제가 가려고하는 경로를 보여줍니다. 추가 조언이 있으면 대단히 감사하겠습니다. – Joe

+0

내 편집 된 답변보기 –

+1

Mmmmmm, Kielbasa. – matt

관련 문제