在UIPanGestureRecognizer之后显示标签

时间:2016-12-19 14:26:20

标签: swift uipangesturerecognizer

我试图在用户向下拖动图片后显示标签。问题是标签不会显示出来。其他一切都很好,但只有标签不起作用。我已经试着找了几个小时的解决方案,但我不知道我做错了什么。

在UIPanGestureRecognizer上调用的函数:

func pullDownView(gesture: UIPanGestureRecognizer) {
    if(gesture.state == .changed) {
        if(iconImage.center.y - (iconImage.frame.size.height / 2) < view.frame.size.height / 3) {
            let translationY = gesture.translation(in: view).y
            iconImage.center.y += translationY

            gesture.setTranslation(CGPoint(x: 0, y: 0), in: view)
            iconImage.updateConstraints()
        }else{
            iconImage.isUserInteractionEnabled = false
            iconImage.center.y = (view.frame.size.height / 3) + (iconImage.frame.size.height / 2)
            iconImage.updateConstraints()
        }
    }

    if(gesture.state == .cancelled || gesture.state == .ended || gesture.state == .failed) {
        if(iconImage.center.y - (iconImage.frame.size.height / 2) >= view.frame.size.height / 6) {
            if(iconImage.center.y != (view.frame.size.height / 3) + (iconImage.frame.size.height / 2)) {
                iconImage.isUserInteractionEnabled = false
                iconImage.center.y = (view.frame.size.height / 3) + (iconImage.frame.size.height / 2)
                iconImage.updateConstraints()

                getAccounts()
            }
        }else{
            iconImage.center.y = view.frame.size.height / 2
            iconImage.updateConstraints()
        }
    }
}

func getAccounts() {
    noAccountsLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 50))
    noAccountsLabel.text = "No accounts found!"
    noAccountsLabel.font = UIFont(name: "Verdana", size: 20)
    noAccountsLabel.textAlignment = .center
    noAccountsLabel.center = CGPoint(x: view.frame.size.width / 2, y: noAccountsLabel.frame.size.height * 2)

    view.addSubview(noAccountsLabel)
}

感谢您的帮助! Steff。

1 个答案:

答案 0 :(得分:1)

func getAccounts() {
  let noAccountsLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 50))
  noAccountsLabel.text = "No accounts found!"
  noAccountsLabel.font = UIFont(name: "Verdana", size: 20)
  noAccountsLabel.textAlignment = .center
  noAccountsLabel.center = CGPoint(x: view.frame.size.width / 2, y: noAccountsLabel.frame.size.height * 2)

  view.addSubview(noAccountsLabel)
}

为我工作。

PS:我可能在这里做错了逻辑,但是你可以使用guard来清除一些if语句:

guard gesture.state == .cancelled || gesture.state == .ended || gesture.state == .failed else  { return }

guard (iconImage.center.y - (iconImage.frame.size.height / 2) >= view.frame.size.height / 6) else { return }

if(iconImage.center.y != (view.frame.size.height / 3) + (iconImage.frame.size.height / 2)) {
  iconImage.isUserInteractionEnabled = false
  iconImage.center.y = (view.frame.size.height / 3) + (iconImage.frame.size.height / 2)
  iconImage.updateConstraints()

  getAccounts()
}