在我的iOS应用中,我必须在UITableView
中列出文档,并且我想将它们与UIImage
相关联。要选择图像,我必须遵循这个方案
如何在UIImage
iOS框架中使用统一类型标识符来选择正确的MobileCoreServices
?
我写了以下swift函数:
public static func image(for pathExtension: String) -> UIImage {
guard let rawUtis = UTTypeCreateAllIdentifiersForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue() as? [String] else {
return #imageLiteral(resourceName: "UNKNOWN")
}
for rawUti in rawUtis {
if UTTypeConformsTo(rawUti as CFString, kUTTypePDF) {
return #imageLiteral(resourceName: "IMAGE2")
}
if UTTypeConformsTo(rawUti as CFString, "com.microsoft.word.doc") || UTTypeConformsTo(rawUti as CFString, "org.openxmlformats.wordprocessingml.document") || UTTypeConformsTo(rawUti as CFString, "org.oasis-open.opendocument.text-template") || UTTypeConformsTo(rawUti as CFString, "org.oasis-open.opendocument.text") || UTTypeConformsTo(rawUti as CFString, "com.microsoft.word.dot") {
return #imageLiteral(resourceName: "IMAGE1")
}
// etc.
}
}
我使用FileKit来管理我的文件'路径。我的cellForRowAt
看起来像
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "documentCell", for: indexPath) as! DocumentViewCell
let documentPath = ... // document's path from indexPath
cell.nameLabel.text = documentPath.fileName
cell.iconImageView?.image = UTI.image(for: documentPath.pathExtension)
// ...
return cell
}
我发现image
功能非常难看。有没有更聪明的方法来实现我的目标?
感谢。