Skip to content
This repository has been archived by the owner on Jul 13, 2022. It is now read-only.

Commit

Permalink
insertArrangedSubview(_:atIndex:) method now updates index in arrange…
Browse files Browse the repository at this point in the history
…dSubviews if view is already arranged
  • Loading branch information
kean committed Mar 15, 2016
1 parent 5c08bc3 commit 2545958
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
16 changes: 16 additions & 0 deletions Example/Tests/SubviewsManagementTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,20 @@ class SubviewsManagementTests: XCTestCase {
XCTAssertFalse(stack.arrangedSubviews.contains(view))
XCTAssertTrue(stack.subviews.contains(view))
}

func testThatInsertArrangedSubivewAtIndexMethodUpdatesIndexOfExistingSubview() {
let stack = StackView()
let view1 = UIView()
let view2 = UIView()
stack.addArrangedSubview(view1)
stack.addArrangedSubview(view2)
XCTAssertEqual(stack.arrangedSubviews.count, 2)
XCTAssertTrue(stack.arrangedSubviews[0] === view1)
XCTAssertTrue(stack.arrangedSubviews[1] === view2)

stack.insertArrangedSubview(view2, atIndex: 0)
XCTAssertEqual(stack.arrangedSubviews.count, 2)
XCTAssertTrue(stack.arrangedSubviews[0] === view2)
XCTAssertTrue(stack.arrangedSubviews[1] === view1)
}
}
17 changes: 9 additions & 8 deletions Sources/StackView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -172,16 +172,17 @@ public class StackView : UIView {
The stack view also ensures that the arrangedSubviews array is always a subset of its subviews array. This method automatically adds the provided view as a subview of the stack view, if it is not already. When adding subviews, the stack view appends the view to the end of its subviews array. The index only affects the order of views in the arrangedSubviews array. It does not affect the ordering of views in the subviews array.
*/
public func insertArrangedSubview(view: UIView, atIndex stackIndex: Int) {
if !arrangedSubviews.contains(view) {
view.translatesAutoresizingMaskIntoConstraints = false
arrangedSubviews.insert(view, atIndex: stackIndex)
if view.superview != self {
addSubview(view)
}
invalidateLayout()
if let idx = arrangedSubviews.indexOf(view) {
arrangedSubviews.removeAtIndex(idx)
}
view.translatesAutoresizingMaskIntoConstraints = false
arrangedSubviews.insert(view, atIndex: stackIndex)
if view.superview != self {
addSubview(view)
}
invalidateLayout()
}

/// Removes subview from arranged subviews.
public override func willRemoveSubview(subview: UIView) {
removeArrangedSubview(subview)
Expand Down

0 comments on commit 2545958

Please sign in to comment.