簡體   English   中英

用文本內的圖像構造UIViewControllers

[英]Structuring UIViewControllers with images inside of text

我必須創建一個具有5個UIViewControllers的應用程序,每個UIViewControllers都有大文本和文本內部的圖像。 到目前為止,我所做的是在UIViewController添加UITextView並使用rtf文件加載整個文本(每個文本都很大)。

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

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

您還可以通過將JavascriptCore.framework添加到構建階段來添加可在swift或obj-c中處理的javascript回調:

在代碼中添加按鈕:

<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")
}

您可以使用NSAttributedStringNSTextAttachment實現此NSTextAttachment 屬性字符串是帶有附加格式(粗體,斜體,顏色等)的字符串,但是您也可以將圖像附加在屬性字符串中,並且它們會隨文本一起正確繪制。 以下示例可以幫助您理解:

//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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM