/Bricks.swift Secret
Created
December 11, 2019 02:52
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import PlaygroundSupport | |
class MyViewController : UIViewController { | |
override func loadView() { | |
let view = UIView() | |
let gradView = GradientView() | |
gradView.frame = view.bounds | |
gradView.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
view.addSubview(gradView) | |
let layout = Layout() | |
layout.delegate = self | |
let cv = UICollectionView(frame: view.bounds, collectionViewLayout: layout) | |
cv.contentInset = .init(top: 10, left: 10, bottom: 10, right: 10) | |
cv.backgroundColor = .clear | |
cv.frame = view.bounds | |
cv.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
cv.dataSource = self | |
cv.register(Cell.self, forCellWithReuseIdentifier: String(describing: Cell.self)) | |
view.addSubview(cv) | |
self.view = view | |
} | |
var words: [String] = { | |
let text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." | |
return text.components(separatedBy: .whitespaces) | |
}() | |
} | |
extension MyViewController: UICollectionViewDataSource { | |
func numberOfSections(in collectionView: UICollectionView) -> Int { | |
return 1 | |
} | |
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { | |
return words.count | |
} | |
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { | |
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: Cell.self), for: indexPath) as! Cell | |
cell.contentView.backgroundColor = .white | |
cell.label.text = string(for: indexPath) | |
return cell | |
} | |
} | |
extension MyViewController: LayoutDelegate { | |
func string(for indexPath: IndexPath) -> String { | |
guard indexPath.row < words.count else { return "" } | |
return words[indexPath.row] | |
} | |
} | |
protocol LayoutDelegate: class { | |
func string(for indexPath: IndexPath) -> String | |
} | |
final class Layout: UICollectionViewLayout { | |
weak var delegate: LayoutDelegate? | |
private var calcResults: [IndexPath : UICollectionViewLayoutAttributes] = [:] | |
//content size | |
private var contentWidth: CGFloat { | |
guard let collectionView = collectionView else { | |
return 0 | |
} | |
let insets = collectionView.contentInset | |
return collectionView.bounds.width - (insets.left + insets.right) | |
} | |
private var contentHeight: CGFloat = 0 | |
//brick size | |
func minimumBrickWidth(forText text: NSString) -> CGFloat { | |
let textWidth = text.boundingRect(with: .init(width: 0, height: brickHeight), attributes: [.font:UIFont.systemFont(ofSize: 14)], context: nil).width | |
return ceil(textWidth + brickSidePadding * 2) | |
} | |
let brickHeight: CGFloat = 40 | |
let brickInsets: UIEdgeInsets = .init(top: 1, left: 1, bottom: 1, right: 1) | |
let brickSidePadding: CGFloat = 16 | |
override func prepare() { | |
super.prepare() | |
guard let collectionView = collectionView else { return } | |
if !calcResults.isEmpty { return } | |
guard let delegate = delegate else { return } | |
let section = 0 | |
var currentPos = CGPoint.zero | |
var results: [[IndexPath : UICollectionViewLayoutAttributes]] = [[:]] | |
for i in 0..<collectionView.numberOfItems(inSection: section) { | |
let indexPath = IndexPath(item: i, section: section) | |
let text = delegate.string(for: indexPath) | |
let minBrickWidth = minimumBrickWidth(forText: text as NSString) | |
let brickFrame: CGRect | |
let surplus = contentWidth - currentPos.x | |
if minBrickWidth <= surplus { | |
//余白が十分にあれば、セルを横に並べる | |
brickFrame = .init(origin: currentPos, size: .init(width: minBrickWidth, height: brickHeight)) | |
} else { | |
//余白が不足していれば、 | |
//1. 現在行に含まれる幅をsurplus分均等に広げる | |
let lastLineArray = results.last!.sorted { | |
$0.value.frame.origin.x < $1.value.frame.origin.x | |
} | |
let bw = surplus / CGFloat(lastLineArray.count) | |
for (i, map) in lastLineArray.enumerated() { | |
let attrs = map.value | |
var newFrame = attrs.frame | |
newFrame.size.width += bw | |
newFrame.origin.x += bw * CGFloat(i) | |
attrs.frame = newFrame | |
} | |
//2. 改行して新しい行にセルを並べる | |
currentPos.x = 0 | |
currentPos.y += brickHeight | |
brickFrame = .init(origin: currentPos, size: .init(width: minBrickWidth, height: brickHeight)) | |
results.append([:]) | |
} | |
currentPos.x += minBrickWidth | |
contentHeight = max(contentHeight, brickFrame.maxY) | |
let attrs = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: i, section: section)) | |
let insetFrame = brickFrame.inset(by: brickInsets) | |
attrs.frame = insetFrame | |
results[results.count - 1][indexPath] = attrs | |
} | |
calcResults = results.reduce([:], { (result, map) -> [IndexPath : UICollectionViewLayoutAttributes] in | |
return result.merging(map) {(item, _) in item} | |
}) | |
} | |
override var collectionViewContentSize: CGSize { | |
return CGSize(width: contentWidth, height: contentHeight) | |
} | |
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { | |
return calcResults.filter { | |
$0.value.frame.intersects(rect) | |
}.map { | |
$0.value | |
} | |
} | |
override func layoutAttributesForItem(at indexPath: IndexPath) | |
-> UICollectionViewLayoutAttributes? { | |
return calcResults[indexPath] | |
} | |
override func invalidateLayout() { | |
super.invalidateLayout() | |
calcResults.removeAll() | |
} | |
} | |
final class Cell: UICollectionViewCell { | |
static let font = UIFont.systemFont(ofSize: 14) | |
let label = UILabel() | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
contentView.layer.cornerCurve = .continuous | |
contentView.layer.cornerRadius = 3 | |
contentView.clipsToBounds = true | |
label.frame = contentView.bounds | |
label.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
label.textAlignment = .center | |
label.font = type(of: self).font | |
label.textColor = UIColor(white: 0.2, alpha: 1.0) | |
contentView.addSubview(label) | |
} | |
required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
} | |
final class GradientView: UIView { | |
let colors: [UIColor] = [.systemRed, .systemBlue] | |
override func draw(_ rect: CGRect) { | |
guard let ctx = UIGraphicsGetCurrentContext() else { return } | |
let clrs = colors.map { $0.cgColor } as CFArray | |
let grad = CGGradient(colorsSpace: nil, colors: clrs, locations: [0, 1])! | |
ctx.drawLinearGradient(grad, start: .zero, end: .init(x: 0, y: rect.height), options: []) | |
} | |
} | |
// Present the view controller in the Live View window | |
PlaygroundPage.current.liveView = MyViewController() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: