'How to use addAttribute in Swift
I'm trying to add links to UITextViews, so I am following the code in this post. The relevant Objective-C code is
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is an example by @marcelofabri_"];
[attributedString addAttribute:NSLinkAttributeName
value:@"username://marcelofabri_"
range:[[attributedString string] rangeOfString:@"@marcelofabri_"]];
But when I try this in Swift 2 as
var attributedString = NSMutableAttributedString(string: "This is an example by @marcelofabri_")
attributedString.addAttribute(NSLinkAttributeName, value: "username://marcelofabri_", range: attributedString.string.rangeOfString("/marcelofabri_"))
I get the error
Cannot invoke 'addAttribute' with an argument list of type '(String, value: String, range: Range?)'
What do I need to change to get this to work?
Solution 1:[1]
Try using NSString to find range instead of Swift String:
var attributedString = NSMutableAttributedString(string: "This is an example by @marcelofabri_")
attributedString.addAttribute(NSLinkAttributeName, value: "username://marcelofabri_", range: (attributedString.string as NSString).rangeOfString("/marcelofabri_"))
Solution 2:[2]
Solution 3:[3]
@available(iOS 14, *)
extension ColorPickerVC: UIColorPickerViewControllerDelegate {
func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) {
print(viewController.selectedColor.hexCode)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "setHexColor"), object: nil, userInfo: ["hexColor": viewController.selectedColor.hexCode])
}
func colorPickerViewControllerDidFinish(_ viewController: UIColorPickerViewController) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "setHexColor"), object: nil, userInfo: ["hexColor": viewController.selectedColor.hexCode])
self.view.backgroundColor = viewController.selectedColor
}
func canPerformSegueWithIdentifier(identifier: NSString) -> Bool {
let templates:NSArray = value(forKey: "storyboardSegueTemplates") as! NSArray
let predicate:NSPredicate = NSPredicate(format: "identifier=%@", identifier)
let filteredtemplates = templates.filtered(using: predicate)
return (filteredtemplates.count>0)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | egor.zhdan |
| Solution 2 | Community |
| Solution 3 | Cody Gray |
