按钮在程序化动态stackView(Swift)中变为非活动状态

时间:2017-07-14 00:07:05

标签: swift button autolayout stackview

我正在尝试在Apple's Auto Layout Cookbook中实现动态堆栈视图的编程版本。 “添加项”按钮应该向垂直stackView添加新视图,包括删除每个视图的删除按钮。我的程序代码适用于“添加项目”按钮的一次触摸,但随后该按钮变为非活动状态。因此,我只能向stackView添加1个项目。如果我使用删除按钮,“添加项目”将再次激活。我已经包含了一个动画GIF来说明。

我发布了我的程序代码(有问题),下面是基于故事板的原始代码(工作正常)。我已经尝试在addEntry函数中放置调试断点,但这没有帮助。 -Thanks

程序代码(“添加项目”按钮仅适用一次):

import UIKit

class CodeDynamStackVC: UIViewController {

  // MARK: Properties
  var scrollView = UIScrollView()
  var stackView = UIStackView()
  var button = UIButton()

  // MARK: UIViewController
  override func viewDidLoad() {
    super.viewDidLoad()
    // Set up the scrollview
    let insets = UIEdgeInsets(top: 20, left: 0.0, bottom: 0.0, right: 0.0)
    scrollView.contentInset = insets
    scrollView.scrollIndicatorInsets = insets
    setupInitialVertStackView()
  }
  //setup initial button inside vertical stackView
  func setupInitialVertStackView() {
    // make inital "Add Item" button
    button = UIButton(type: .system)
    button.setTitle("Add Item", for: .normal)
    button.setTitleColor(UIColor.blue, for: .normal)
    button.addTarget(self, action: #selector(addEntry), for: .touchUpInside)
    //enclose button in a vertical stackView
    stackView.addArrangedSubview(button)
    stackView.axis = .vertical
    stackView.alignment = .fill
    stackView.distribution = .equalSpacing
    stackView.spacing = 5
    stackView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(stackView)
    let viewsDictionary = ["v0":stackView]
    let stackView_H = NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
    let stackView_V = NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[v0(25)]|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: viewsDictionary)
    view.addConstraints(stackView_H)
    view.addConstraints(stackView_V)
  }

  // MARK: Interface Builder actions
  func addEntry() {
    guard let addButtonContainerView = stackView.arrangedSubviews.last else { fatalError("Expected at least one arranged view in the stack view.") }
    let nextEntryIndex = stackView.arrangedSubviews.count - 1
    let offset = CGPoint(x: scrollView.contentOffset.x, y: scrollView.contentOffset.y + addButtonContainerView.bounds.size.height)
    let newEntryView = createEntryView()
    newEntryView.isHidden = true
    stackView.insertArrangedSubview(newEntryView, at: nextEntryIndex)
    UIView.animate(withDuration: 0.25, animations: {
      newEntryView.isHidden = false
      self.scrollView.contentOffset = offset
    })
  }

  func deleteStackView(_ sender: UIButton) {
    guard let entryView = sender.superview else { return }
    UIView.animate(withDuration: 0.25, animations: {
      entryView.isHidden = true
    }, completion: { _ in
      entryView.removeFromSuperview()
    })
  }

  // MARK: Convenience

  /// Creates a horizontal stackView entry to place within the parent vertical stackView
  fileprivate func createEntryView() -> UIView {
    let date = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .none)
    let number = UUID().uuidString
    let stack = UIStackView()
    stack.axis = .horizontal
    stack.alignment = .center
    stack.distribution = .fill
    stack.spacing = 8

    let dateLabel = UILabel()
    dateLabel.text = date
    dateLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)

    let numberLabel = UILabel()
    numberLabel.text = number
    numberLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption2)
    numberLabel.setContentHuggingPriority(UILayoutPriorityDefaultLow - 1.0, for: .horizontal)
    numberLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultHigh - 1.0, for: .horizontal)

    let deleteButton = UIButton(type: .roundedRect)
    deleteButton.setTitle("Del", for: UIControlState())
    deleteButton.addTarget(self, action: #selector(DynamStackVC.deleteStackView(_:)), for: .touchUpInside)

    stack.addArrangedSubview(dateLabel)
    stack.addArrangedSubview(numberLabel)
    stack.addArrangedSubview(deleteButton)

    return stack
  }
}

基于故事板的代码(“添加项目”按钮始终有效)

import UIKit

class DynamStackVC: UIViewController {

    // MARK: Properties

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var stackView: UIStackView!

    // MARK: UIViewController

    override func viewDidLoad() {
      super.viewDidLoad()

      // Set up the scrollview.
      let insets = UIEdgeInsets(top: 20, left: 0.0, bottom: 0.0, right: 0.0)
      scrollView.contentInset = insets
      scrollView.scrollIndicatorInsets = insets
    }

    // MARK: Interface Builder actions

    @IBAction func addEntry(_: AnyObject) {
      guard let addButtonContainerView = stackView.arrangedSubviews.last else { fatalError("Expected at least one arranged view in the stack view.") }
      let nextEntryIndex = stackView.arrangedSubviews.count - 1

      let offset = CGPoint(x: scrollView.contentOffset.x, y: scrollView.contentOffset.y + addButtonContainerView.bounds.size.height)

      let newEntryView = createEntryView()
      newEntryView.isHidden = true

      stackView.insertArrangedSubview(newEntryView, at: nextEntryIndex)

      UIView.animate(withDuration: 0.25, animations: {
        newEntryView.isHidden = false
        self.scrollView.contentOffset = offset
      })
    }

    func deleteStackView(_ sender: UIButton) {
      guard let entryView = sender.superview else { return }

      UIView.animate(withDuration: 0.25, animations: {
        entryView.isHidden = true
      }, completion: { _ in
        entryView.removeFromSuperview()
      })
    }

    // MARK: Convenience

    /// Creates a horizontal stack view entry to place within the parent `stackView`.
    fileprivate func createEntryView() -> UIView {
      let date = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .none)
      let number = UUID().uuidString

      let stack = UIStackView()
      stack.axis = .horizontal
      stack.alignment = .center
      stack.distribution = .fillProportionally
      stack.spacing = 8

      let dateLabel = UILabel()
      dateLabel.text = date
      dateLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)

      let numberLabel = UILabel()
      numberLabel.text = number
      numberLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption2)
      numberLabel.setContentHuggingPriority(UILayoutPriorityDefaultLow - 1.0, for: .horizontal)
      numberLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultHigh - 1.0, for: .horizontal)

      let deleteButton = UIButton(type: .roundedRect)
      deleteButton.setTitle("Del", for: UIControlState())
      deleteButton.addTarget(self, action: #selector(DynamStackVC.deleteStackView(_:)), for: .touchUpInside)

      stack.addArrangedSubview(dateLabel)
      stack.addArrangedSubview(numberLabel)
      stack.addArrangedSubview(deleteButton)

      return stack
    }
}

enter image description here

1 个答案:

答案 0 :(得分:0)

我通过在动态stackView中的所有按钮和标签上添加背景颜色来解决这个问题。正如您在新动画gif中看到的那样,按下第一个按钮后,“添加项目”按钮的青色消失。为了确认,我将按钮的原始高度加倍(即,从gif左侧的(25)到(50)),然后在不再工作之前按下两个按钮,青色背景消失。这教会了我很多关于动态stackView如何工作的东西,我希望它能帮助别人。 enter image description here