UIView changing its position in swift

前端 未结 4 2006
难免孤独
难免孤独 2021-01-31 10:21

How do I make a UIView slide up with a touch of a button from its original position and them bring it back down with a touch of a button? Using Swift and Xcode 6.

4条回答
  •  情歌与酒
    2021-01-31 10:45

     // MARK: - Properties
    
    var bottomViewHeight: CGFloat = 200
    var isViewHide = false
    
    private let bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .red
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    private let showHideButton: UIButton = {
        let button = UIButton()
        button.setTitle("Show / Hide", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(showHideButtonTapped(_:)), for: .touchUpInside)
        return button
    }()
    
    // MARK: - Lifecycle
    
    override func loadView() {
        super.loadView()
    
        view.addSubview(bottomView)
    
        NSLayoutConstraint.activate([
            bottomView.heightAnchor.constraint(equalToConstant: bottomViewHeight),
            bottomView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            bottomView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
            bottomView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
        ])
    
        view.addSubview(showHideButton)
    
        NSLayoutConstraint.activate([
            showHideButton.widthAnchor.constraint(equalToConstant: 200),
            showHideButton.heightAnchor.constraint(equalToConstant: 50),
            showHideButton.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
            showHideButton.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor)
        ])
    
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        showHideView(isShow: isViewHide)
    
    }
    
    // MARK: - Selectors
    
    @objc func showHideButtonTapped(_ sender: UIButton) {
        print("

提交回复
热议问题