获取Swift中导航栏项目按钮的位置

时间:2020-01-16 13:03:29

标签: swift uinavigationcontroller uinavigationbar uinavigationitem cgpoint

我想获取导航项的位置(点),它是一个按钮。如果可以获取此点,则可以在我的应用中添加一个引导圈。但是我不能正确地指出这一点。

let point = searchBarButton.center

let point = view.convert(CGPoint(x: searchBarButton.center.x, y: searchBarButton.center.y + UIApplication.shared.statusBarFrame.height), from: view)
添加状态栏高度时,正确计算了

y点。但是x点的值始终为20,这没有任何意义。那么如何正确获得x点呢?

这是我的代码和我的应用的屏幕截图。

class ViewController: UIViewController {

    let searchBarButton = UIButton()

    // MARK: - viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()

        configureNavigationBarItems()

        let added_view: UIView = navigationController?.view ?? view
        let point = added_view.convert(CGPoint(x: searchBarButton.center.x, y: searchBarButton.center.y + UIApplication.shared.statusBarFrame.height), from: added_view)
        addCircle(point: point)

    }

    func configureNavigationBarItems() {

        searchBarButton.setImage(UIImage(named: "icon_search_border"), for: .normal)
        searchBarButton.frame = CGRect.init(x: 0, y: 0, width: 40, height: 40)
        let searchBarButtonItem = UIBarButtonItem.init(customView: searchBarButton)

        self.navigationItem.setRightBarButton(searchBarButtonItem, animated: true)

    }

    func addCircle(point: CGPoint) {

        let overlayView = UIView(frame: self.view.bounds)
        overlayView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        self.navigationController?.view.addSubview(overlayView)

        let circlePath = UIBezierPath(arcCenter: point,
                                      radius: 30,
                                      startAngle: 0.0,
                                      endAngle: 2.0 * .pi,
                                      clockwise: true)

        let path = CGMutablePath()
        path.addPath(circlePath.cgPath)
        path.addRect(overlayView.frame)

        let maskLayer = CAShapeLayer()
        maskLayer.path = path
        maskLayer.fillRule = .evenOdd

        overlayView.layer.mask = maskLayer
        overlayView.layer.masksToBounds = true

    }

}

screenshot

0 个答案:

没有答案
相关问题