hsusmita / ResponsiveLabel

MIT License
218 stars 36 forks source link

Swift 2.0: Value of type 'PatternTapResponder' (aka 'ImplicitlyUnwrappedOptional<String> -> ()') does not conform to expected dictionary value type 'AnyObject' #30

Open AshwinDamji opened 8 years ago

AshwinDamji commented 8 years ago

Hi,

I am using Swift 2.0 I have written below code.

let expansionToken = "...More"
        let tapResponderAction: PatternTapResponder = { (tappedString) -> Void in
            print("User Tapped More = " + tappedString)
            review.isExpanded = !review.isExpanded
            tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

        }

        let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: expansionToken, attributes: [NSForegroundColorAttributeName: UIColor(r: 137, g: 135, b: 135), NSFontAttributeName: UIFont(gothamRegularSize: 9), **RLTapResponderAttributeName: tapResponderAction**])

        cell.lblReview.setAttributedTruncationToken(attributedText)
        cell.lblReview.setText(reviewText, withTruncation: true)

The above bold line gives following error: Value of type 'PatternTapResponder' (aka 'ImplicitlyUnwrappedOptional -> ()') does not conform to expected dictionary value type 'AnyObject'

And also when I write

[RLTapResponderAttributeName: tapResponderAction as! AnyObject]

into dictionary below errors occur at runtime.

Could not cast value of type 'Swift.ImplicitlyUnwrappedOptional -> ()' (0x11d334080) to 'Swift.AnyObject' (0x11be6c018)

stevenmunoz commented 8 years ago

I'm having the same issue, some answers ?

vcambur commented 8 years ago

something like

let block: @convention(block) (NSString!) -> Void = {
    (string: NSString!) -> Void in
        print(string)
}
label.enableStringDetection("test string", withAttributes: [NSForegroundColorAttributeName: UIColor.redColor(), RLTapResponderAttributeName: unsafeBitCast(block, AnyObject.self)])

seems to do the trick

hb2708 commented 8 years ago

@vcambur Thanks

Worked for me.

DavidWittix commented 6 years ago

Shorten version of @vcambur is:

extension NSAttributedString.Key {
    static var tap: String {
        return RLTapResponderAttributeName
    }
}

func Tap(responder: @escaping (String) -> Void) -> AnyObject {
    let block: @convention(block) (NSString!) -> Void = {
        (string: NSString!) -> Void in
        responder(string as String)
    }
    return unsafeBitCast(block, to: AnyObject.self)
}

usage:

label.enableStringDetection("test string", withAttributes: [
    NSAttributedString.Key.tap: Tap { text in
        print(text)
    },
])