How to add a hover effect to a UITableViewCell (Swift)

When iPadOS 13.4 was released so was much improved Mouse-Pointer support. While a non starter on your iPhone, iPad with a trackpad and external keyboard quickly turns into a very capable computing device.

For my app – Open Access Helper – I wanted to support this feature, even if it wouldn’t be used a lot. For most UI Elements, such as Buttons it can be as easy as adding something like the following to your ViewDidLoad method:

if #available(iOS 13.4, *) {
    helpButton.isPointerInteractionEnabled = true
    searchButton.isPointerInteractionEnabled = true
}

VoilĂ  – those buttons suddenly support the Mouse Pointer interaction. What proved harder was to actually provide a hover effect on TableViews.

It probably just boils down to me not understanding the documentation and possible not “googling” the problem quite right, but I eventually figured out how to do it.

The trick is that you need to apply the effect to your UITableViewCell. In your awakeFromNib() you configure the interaction, i.e. by calling an appropriate method for those devices in iOS 13.4 or higher.

Below a super basic “GenericTableViewCell” Class, that does nothing but show the implementation.

import UIKit

class GenericTableViewCell: UITableViewCell, UIPointerInteractionDelegate {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        if #available(iOS 13.4, *) {
            configurePointer()
        }
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }

    
    @available(iOS 13.4, *)
    func configurePointer() {
        let interaction = UIPointerInteraction(delegate: self)
        addInteraction(interaction)
    }

    // MARK: - UIPointerInteractionDelegate -
    @available(iOS 13.4, *)
    public func pointerInteraction(_ interaction: UIPointerInteraction, styleFor region: UIPointerRegion) -> UIPointerStyle? {
        var pointerStyle: UIPointerStyle?
        if let interactionView = interaction.view {
            let targetedPreview = UITargetedPreview(view: interactionView)
            pointerStyle = UIPointerStyle(effect: UIPointerEffect.highlight(targetedPreview))
        }
        return pointerStyle
    }
}
How to add a hover effect to a UITableViewCell (Swift)
Scroll to top