我试图通过向上滑动显示屏幕底部的视图并通过向下滑动隐藏它。我在屏幕中央有一个标签,我希望将其带到高度的1/4点,因为视图占据屏幕的一半。那部分工作正常,但是当我想隐藏视图时将其恢复到原始位置时,它似乎不起作用并且在高度的1/4处重新调整。
anyobdy知道这里的问题是什么吗?
以下是我的代码:
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit
class SecondViewController: UIViewController {
let label = UILabel()
var v = MyCustomView()
override func viewDidLoad() {
super.viewDidLoad()
FBSDKGraphRequest(graphPath: "/me", parameters: ["Fields" : "name"]).start {
(connection, result, err) in
if err != nil {
print("Failed to start request", err)
return
}
var res = result as? [String : Any]
myVars.username = (res?["name"] as! String)
print(myVars.username)
}
self.v = MyCustomView(frame: CGRect(x: 0, y: view.bounds.height / 2, width: view.bounds.width, height: view.bounds.height / 2))
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
let lblHeight = label.heightAnchor.constraint(equalToConstant : 30)
let lblWidth = label.widthAnchor.constraint(equalToConstant: 200)
let yConstraint = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: view.bounds.height / 2.0 - 15)
let xConstraint = NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: view.bounds.width / 2.0 - 100)
NSLayoutConstraint.activate([lblHeight,lblWidth,xConstraint,yConstraint])
label.backgroundColor = UIColor.red
label.textAlignment = NSTextAlignment.center
label.text = "Shit comes up here!"
let swipeUp = UISwipeGestureRecognizer(target: self, action: "swipeUp")
swipeUp.direction = UISwipeGestureRecognizerDirection.up
self.view.addGestureRecognizer(swipeUp)
let swipeDown = UISwipeGestureRecognizer(target: self, action: "swipeDown")
swipeDown.direction = UISwipeGestureRecognizerDirection.down
self.view.addGestureRecognizer(swipeDown)
}
struct myVars{
static var username = "X"
}
func swipeUp(){
if v.isDescendant(of : self.view) {
v.isHidden = false
}
else {
self.label.text = myVars.username
self.view.addSubview(v)
}
let yConstraint = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: view.bounds.height / 4.0 - 15)
NSLayoutConstraint.activate([yConstraint])
}
func swipeDown(){
let yConstraint = NSLayoutConstraint(item : label, attribute : .top, relatedBy: .equal, toItem: view, attribute : .top, multiplier: 1, constant: view.bounds.height / 2.0 - 15)
NSLayoutConstraint.activate([yConstraint])
print("SwipedDown!")
v.isHidden = true
}
}