2016-08-12 16 views
0

我必須創建一個應用程序,其中每個文本都帶有大文本和圖像。到目前爲止,我所做的是在UIViewController中添加一個UITextView,並用一個rtf文件加載全文(每個文本都很大)。用文本內部的圖像構造UIViewControllers

現在我必須在一些地方的文字裏添加圖像。你建議什麼可能是構建它的最好方法?我試圖在rtf文件中添加圖像,但無法正常工作。由於文字太大,我不想通過鍵入來手動添加文本。另外,我有一個頂部欄菜單,可將視圖滑動到每個內容,這就是爲什麼我只需要一個UITextView。我正在尋找最佳解決方案。

回答

2

如何在UIWebView中添加帶有圖像的文本,並通過將這些文本包裝到html中來加載這些文本?

你也可以通過添加JavascriptCore.framework到您的構建階段添加JavaScript回調,您將能夠在迅速或OBJ-C處理:

在代碼中添加按鈕:

<button text="Close" onclick="javascript:callSwiftCode()">Call swift code</button> 

而在你UIWebViewDelegate類:

func webViewDidFinishLoad(webView: UIWebView) { 
    let context: JSContext = webView.valueForKeyPath("documentView.webView.mainFrame.javaScriptContext") as! JSContext 

    let codeClosure: @convention(block)()->() = {()->() in 
     print ("This is callback from javascript you can add your code in this closure") 
    } 

    let casted: AnyObject = unsafeBitCast(codeClosure, AnyObject.self) as AnyObject 
    context.setObject(casted, forKeyedSubscript: "callSwiftCode") 
} 
+0

這是一個非常好的主意。感謝您的答覆。但還有一件事。我可以在打開其他圖像的html文件中添加一個按鈕嗎?那可能嗎? – user3882720

+0

這應該是可以直接在HTML中。如果你想對應用程序的本地代碼進行適當的掛鉤(對於不同的東西),我建議使用'WKWebView'和'WKUserContentController'的'addScriptMessageHandler:name:'方法來安裝java腳本監聽器。 – Gero

+0

是的。查看編輯文章 –

0

爲此,可以使用NSAttributedStringNSTextAttachment實現。歸屬字符串是附帶格式(粗體,斜體,顏色等)的字符串,但您也可以將圖像附加到屬性字符串中,並且只需將它們與文本一起繪製。下面的例子可能會幫助你理解:

//Create a mutable attributed string so that we could append everything to it. 
let bigText = NSMutableAttributedString(string: "Your text starts here") 

//Create a NSTextAttachment 
let image1Attachment = NSTextAttachment() 
image1Attachment.image = UIImage(named: "image1.png") 

// wrap the attachment in its own attributed string so we can append it 
let image1String = NSAttributedString(attachment: image1Attachment) 

// add the NSTextAttachment wrapper to our full string, then add some more text. 
bigText.appendAttributedString(image1String) 
bigText.appendAttributedString(NSAttributedString(string: "End of text")) 

// Then set this bigText to your label's attributedText property. 
yourLabel.attributedText = bigText 
+0

是的,但仍然需要在(string:「」)中輸入整個文本。而我的文字太大了。 – user3882720