【发布时间】:2018-02-17 15:33:30
【问题描述】:
我构建了一个自定义视图作为 UIView 的子类。现在,我想在我的 ViewController 中设置这个视图的约束,而不是设置框架。这是自定义视图类:
PullUpView.swift
//
// PullUpView.swift
//
//
import UIKit
final internal class PullUpView: UIView, UIGestureRecognizerDelegate {
// MARK: - Variables
private var animator : UIDynamicAnimator!
private var collisionBehavior : UICollisionBehavior!
private var snapBehaviour : UISnapBehavior?
private var dynamicItemBehavior : UIDynamicItemBehavior!
private var gravityBehavior : UIGravityBehavior!
private var panGestureRecognizer : UIPanGestureRecognizer!
internal var delegate : PullUpViewDelegate?
// MARK: - Setup the view when bounds are defined.
override var bounds: CGRect {
didSet {
print(self.frame)
print(self.bounds)
setupStyle()
setupBehavior()
setupPanGesture()
}
}
override var frame: CGRect {
didSet {
print(self.frame)
print(self.bounds)
setupStyle()
setupBehavior()
setupPanGesture()
}
}
}
// MARK: - Behavior (Collision, Gravity, etc.)
private extension PullUpView {
final private func setupBehavior() {
guard let superview = superview else { return }
animator = UIDynamicAnimator(referenceView: superview)
dynamicItemBehavior = UIDynamicItemBehavior(items: [self])
dynamicItemBehavior.allowsRotation = false
dynamicItemBehavior.elasticity = 0
gravityBehavior = UIGravityBehavior(items: [self])
gravityBehavior.gravityDirection = CGVector(dx: 0, dy: 1)
collisionBehavior = UICollisionBehavior(items: [self])
configureContainer()
animator.addBehavior(gravityBehavior)
animator.addBehavior(dynamicItemBehavior)
animator.addBehavior(collisionBehavior)
}
final private func configureContainer() {
let boundaryWidth = UIScreen.main.bounds.size.width
let boundaryHeight = UIScreen.main.bounds.size.height
collisionBehavior.addBoundary(withIdentifier: "upper" as NSCopying, from: CGPoint(x: 0, y: 0), to: CGPoint(x: boundaryWidth, y: 0))
collisionBehavior.addBoundary(withIdentifier: "lower" as NSCopying, from: CGPoint(x: 0, y: boundaryHeight + self.frame.height - 66), to: CGPoint(x: boundaryWidth, y: boundaryHeight + self.frame.height - 66))
}
final private func snapToBottom() {
gravityBehavior.gravityDirection = CGVector(dx: 0, dy: 2.5)
}
final private func snapToTop() {
gravityBehavior.gravityDirection = CGVector(dx: 0, dy: -2.5)
}
}
// MARK: - Style (Corner-radius, background, etc.)
private extension PullUpView {
final private func setupStyle() {
self.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0)
let blurEffect = UIBlurEffect(style: .regular)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = self.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.addSubview(blurEffectView)
self.layer.masksToBounds = true
self.clipsToBounds = true
self.isUserInteractionEnabled = true
let dragBar = UIView()
dragBar.backgroundColor = .gray
dragBar.frame = CGRect(x: (self.bounds.width / 2) - 5, y: self.bounds.origin.y + 5, width: 10, height: 2)
self.addSubview(dragBar)
}
}
// MARK: - Pan Gesture Recognizer and Handler Functions
internal extension PullUpView {
final private func setupPanGesture() {
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
panGestureRecognizer.cancelsTouchesInView = false
self.addGestureRecognizer(panGestureRecognizer)
}
@objc final private func handlePanGesture(_ panGestureRecognizer: UIPanGestureRecognizer) {
guard let superview = superview else { return }
if let viewCanMove: Bool = delegate?.viewCanMove?(pullUpView: self) {
if !viewCanMove {
return
}
}
let velocity = panGestureRecognizer.velocity(in: superview).y
var movement = self.frame
movement.origin.x = 0
movement.origin.y = movement.origin.y + (velocity * 0.05)
if panGestureRecognizer.state == .ended {
panGestureEnded()
} else if panGestureRecognizer.state == .began {
snapToBottom()
} else {
animator.removeBehavior(snapBehaviour ?? UIPushBehavior())
snapBehaviour = UISnapBehavior(item: self, snapTo: CGPoint(x: movement.midX, y: movement.midY))
animator.addBehavior(snapBehaviour ?? UIPushBehavior())
}
}
final private func panGestureEnded() {
animator.removeBehavior(snapBehaviour ?? UIPushBehavior())
let velocity = dynamicItemBehavior.linearVelocity(for: self)
if fabsf(Float(velocity.y)) > 250 {
if velocity.y < 0 {
moveViewIfPossible(direction: .up)
} else {
moveViewIfPossible(direction: .down)
}
} else {
if let superviewHeight = self.superview?.bounds.size.height {
// User scrolled over half of the screen...
if self.frame.origin.y > superviewHeight / 2 {
moveViewIfPossible(direction: .down)
} else {
moveViewIfPossible(direction: .up)
}
}
}
}
final private func moveViewIfPossible(direction: PullUpViewPanDirection) {
if let viewCanMove: Bool = delegate?.viewCanSnap?(pullUpView: self, direction: direction) {
if viewCanMove {
delegate?.viewWillMove?(pullUpView: self, direction: direction)
direction == .up ? snapToTop() : snapToBottom()
}
} else {
delegate?.viewWillMove?(pullUpView: self, direction: direction)
direction == .up ? snapToTop() : snapToBottom()
}
}
}
// MARK: - PullUpViewPanDirection declared inside
internal extension PullUpView {
/// An enum that defines whether the view moves up or down.
@objc
internal enum PullUpViewPanDirection: Int {
case
up,
down
}
}
但是当我设置约束时,我总是得到一个负原点的框架:
ViewController.swift
pullUpView.translatesAutoresizingMaskIntoConstraints = false
pullUpView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
pullUpView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
pullUpView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
pullUpView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
框架:
(-160.0、-252.0、320.0、504.0)
界限:
(0.0, 0.0, 320.0, 504.0)
奇怪的是,如果我注释掉函数setupBehavior(),视图显示正确(但一旦触发平移手势处理程序就会失败)。
相反,如果我设置 frame:
pullUpView.frame = CGRect(x: 0, y: self.view.bounds.height - 66, width: self.view.bounds.width, height: self.view.bounds.height)
它工作正常。
提前感谢您的帮助!
【问题讨论】:
-
我认为您的第一个错误是在使用自动布局时考虑框架。简而言之,它们不能一起工作。其次,只是使用视图生命周期——而不是滥用它。对于
override边界和框架来说,这可能看起来像是可靠的逻辑,但为什么呢?如果您想使用约束,只需接受操作系统会这样做。在viewDidLoad中设置您的约束,而不用担心边界和框架...接受到时间viewWillLayoutSubviews和viewDidLayoutSubviews事情会在那里。在边界和框架上覆盖didSet?使用自动布局时完全错误的事情。 -
@dfd 但是如果我不覆盖框架或边界,我将如何以及在哪里调用 setup***() 函数?你能写一个答案吗?
-
我不确定您所说的“setup***() 函数”是什么意思。我会给你一个例子作为答案 - 降价可能会有所帮助 - 如果答案没有帮助,请告诉我我会删除它。
-
谢谢!我在谈论 setupStyle()、setupBehavior() 和 setupPanGesture()。它们在 didSet() 中被调用。
-
由于您的问题标题,我专注于“约束”。但据我所知,我认为大多数事情都可以简单地在
viewDidLoad中完成,因为你真的想一次而不是多次做这些事情。