Swift 开发笔记5 - 交换位置的View

2020-08-11  本文已影响0人  feb961880dc1
class ExChangeView: UIView {
    private var fromTitle =  "标题1"
    private lazy var fromButton: UIButton = {
        let button = UIButton()
        button.setTitle(fromTitle, for: .normal)
        return button
    }()
    private var toTitle =  "标题2"
    private lazy var toButton: UIButton = {
        let button = UIButton()
        button.setTitle(toTitle, for: .normal)
        return button
    }()
    private lazy var exchangeButton: UIButton = {
        let button = UIButton()
        button.setTitle("交换", for: .normal)
        button.addTarget(self, action: #selector(exchangeTap), for: .touchDown)
        return button
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLayout()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupLayout() {
        addSubview(exchangeButton)
        exchangeButton.snp.makeConstraints {
            $0.size.equalTo(kSize(16))
            $0.center.equalToSuperview()
        }
        
        addSubview(fromButton)
        fromButton.snp.makeConstraints {
            $0.centerY.equalToSuperview()
            $0.right.equalTo(exchangeButton.snp.left).offset(-kSize(10))
            $0.left.equalTo(kSize(10))
        }
        
        addSubview(toButton)
        toButton.snp.makeConstraints {
            $0.centerY.equalToSuperview()
            $0.left.equalTo(exchangeButton.snp.right).offset(kSize(10))
            $0.right.equalTo(-kSize(10))
        }
    }
    @objc func exchangeTap() {
        guard let fromSnap = fromButton.snapshotView(afterScreenUpdates: false), let toSnap = toButton.snapshotView(afterScreenUpdates: false) else { return }
        
        (toTitle, fromTitle) = (fromTitle, toTitle)
        
        fromButton.setTitle(fromTitle, for: .normal)
        fromButton.alpha = 0
        fromSnap.frame = fromButton.frame
        addSubview(fromSnap)
        
        toButton.setTitle(toTitle, for: .normal)
        toButton.alpha = 0
        toSnap.frame = toButton.frame
        addSubview(toSnap)
        
        UIView.animate(withDuration: 0.4, animations: {
            (fromSnap.frame,toSnap.frame) = (toSnap.frame, fromSnap.frame)
        }) { (complete) in
            self.fromButton.alpha = 1
            fromSnap.removeFromSuperview()
            self.toButton.alpha = 1
            toSnap.removeFromSuperview()
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读