图像后跟使用 UITextView 的垂直列表格式的文本

Image followed by Text in vertical list format using a UITextView

我有一个 tableView,其中的单元格加载了 list.For 例如,当前单元格可能是纯色背景,上面有一个列表,就像这样

Milk
Eggs
Tomatoes

正在从数据源中填充列表,因此要放置在每个单元格中的数量是未知的。我目前正在使用 UITextView 进行操作,如下所示。

var joinedArray = [String]()
cell.textView.text = joinedArray.joined(separator: "\n")

我想在每一行的单词左侧添加图片。所以例如我会

"milk picture" Milk 
"EGGS Picture" Eggs 
"Tomatoes Pic" Tomatoes 

如果我有第二个图片数组,是否可以使用属性字符串将它们添加到 UITextView 中的每个单词之前(在每个换行符的开头)或 attachments.Something 就像所做的那样here.

would it be possible to add [UIImage] into the UITextView before each word?

是的,但是...,默认情况下,UITableViewCell 有一个显示在默认标签左侧的图像视图。

https://developer.apple.com/documentation/uikit/uitableviewcell/1623270-imageview

在您的 tableView(_:cellForRowAt:) 中,根据单元格标题将单元格 ImageView 的图像设置为您的特定图像:

...
//Image of milk in xcassets.images.
cell.imageView.image = UIImage(named: "milk.png")!
// or from your array of images:
cell.imageView.image = 
...

否则我建议创建自定义 tableViewCell programmatically 或在界面生成器中。 google 搜索 "custom table view cell" 提取了大量资源。

如果您仍然想将它添加到 UITextView 的属性文本中,您可以创建一个 for 循环来遍历数组中的元素并生成属性文本,假设您有一个图像数组并且每个图像都有相应的文本,即每个数组的长度相同:

func generateTextFrom(_ images:[UIImage], text:[String]) -> NSMutableAttributedString {
    let fullText = NSMutableAttributedString(string: "")

    for i in 0..<text.count {
        // Create our NSTextAttachment to attach the image
        let imageAttachment = NSTextAttachment()
        imageAttachment.image = images[i]

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

        // Then, the text
        let textItem = NSAttributedString(string: text[i])

        //Then append the text to image, then to fullText
        fullText.append(imageString)
        fullText.append(textItem)
        fullText.append(NSAttributedString(string: "\n"))
    }

    // finally set the textview's attributed text.
    return fullText
}