更新:
我的问题有两个关键部分:
如何创建一个链接,其中显示的可点击链接的文本与被调用的实际链接不同:
如何在不使用自定义代码设置文本属性的情况下设置链接。
iOS 7增加了从NSData中加载属性文本的功能。
我创建了一个UITextView的自定义子类,它利用了@IBInspectable属性,让你直接在IB中加载RTF文件中的内容。
以下是细节:
In iOS 7, NSAttributedString gained the method initWithData:options:documentAttributes:error:. That method lets you load an NSAttributedString from an NSData object. You can first load an RTF file into NSData, then use initWithData:options:documentAttributes:error: to load that NSData into your text view. (Note that there is also a method initWithFileURL:options:documentAttributes:error: that will load an attributed string directly from a file, but that method was deprecated in iOS 9. It's safer to use the method initWithData:options:documentAttributes:error:, which wasn't deprecated.
我想要一种方法,让我安装可点击的链接到我的文本视图,而不必创建任何特定于我正在使用的链接的代码。
我想出的解决方案是创建一个UITextView的自定义子类,我调用RTF_UITextView并给它一个名为RTF_Filename的@IBInspectable属性。将@IBInspectable属性添加到属性中会导致接口构建器在“属性检查器”中公开该属性。然后,您可以从IB设置该值,而无需自定义代码。
I also added an @IBDesignable attribute to my custom class. The @IBDesignable attribute tells Xcode that it should install a running copy of your custom view class into Interface builder so you can see it in the graphical display of your view hierarchy. ()Unfortunately, for this class, the @IBDesignable property seems to be flaky. It worked when I first added it, but then I deleted the plain text contents of my text view and the clickable links in my view went away and I have not been able to get them back.)
RTF_UITextView的代码非常简单。除了添加@IBDesignable属性和@IBInspectable属性的RTF_Filename属性外,我还添加了一个didSet()方法到RTF_Filename属性。当RTF_Filename属性的值发生变化时,didSet()方法将被调用。didSet()方法的代码非常简单:
@IBDesignable
class RTF_UITextView: UITextView
{
@IBInspectable
var RTF_Filename: String?
{
didSet(newValue)
{
//If the RTF_Filename is nil or the empty string, don't do anything
if ((RTF_Filename ?? "").isEmpty)
{
return
}
//Use optional binding to try to get an URL to the
//specified filename in the app bundle. If that succeeds, try to load
//NSData from the file.
if let fileURL = NSBundle.mainBundle().URLForResource(RTF_Filename, withExtension: "rtf"),
//If the fileURL loads, also try to load NSData from the URL.
let theData = NSData(contentsOfURL: fileURL)
{
var aString:NSAttributedString
do
{
//Try to load an NSAttributedString from the data
try
aString = NSAttributedString(data: theData,
options: [:],
documentAttributes: nil
)
//If it succeeds, install the attributed string into the field.
self.attributedText = aString;
}
catch
{
print("Nerp.");
}
}
}
}
}
注意,如果@IBDesignable属性不能可靠地让你在Interface builder中预览样式文本,那么将上述代码设置为UITextView的扩展而不是自定义子类可能会更好。这样,您就可以在任何文本视图中使用它,而不必将文本视图更改为自定义类。
如果你需要支持iOS 7之前的iOS版本,请参阅我的其他答案。
你可以从gitHub下载一个包含这个新类的示例项目:
Github上的DatesInSwift演示项目