Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I round the corners of the sourceRect for Peek and Pop 3D Touch?

In Safari, if you use 3D touch, the sourceRect of the link that is being touched has rounded corners. When I set the source rect in: func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {on previewingContext, I can only set previewingContext.sourceRect which doesn't allow me to round the corners, or set a multi corner area. How can I do this?

like image 957
SirRupertIII Avatar asked Oct 18 '22 20:10

SirRupertIII


1 Answers

You can indirectly set round corners to the sourceRect by adding a corner radius to the sourceView's layer. The when you set previewingContext.sourceRect to the sourceView's bounds, the area that stays in focus will also have the rounded corners.

Here is an example that uses a pressable UILabel:

class ViewController: UIViewController {

    var previewingContext: UIViewControllerPreviewing?
    let label = UILabel(frame: CGRectMake(150, 250, 100, 50))

    override func viewDidLoad() {
        super.viewDidLoad()

        let background = UIImageView(frame: view.bounds)
        background.image = UIImage(named: "image.jpg")
        view.addSubview(background)

        label.backgroundColor = UIColor.whiteColor()
        label.text = "Press me!"
        label.textAlignment = .Center
        label.layer.cornerRadius = 20
        label.clipsToBounds = true
        label.userInteractionEnabled = true
        view.addSubview(label)

        previewingContext = registerForPreviewingWithDelegate(self, sourceView: label)
    }
}

extension ViewController: UIViewControllerPreviewingDelegate {

    func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
        previewingContext.sourceRect = label.bounds

        return UIViewController()
    }

    func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
        showViewController(viewControllerToCommit, sender: self)
    }
}

enter image description here

like image 76
joern Avatar answered Jan 04 '23 18:01

joern