Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class HorizontalScrollGrid: UIScrollView {
- public var arrTitles: [String] = []
- public var itemHeight: CGFloat = 45.0
- public var verticalSpacing: CGFloat = 10.0
- public var horizontalSpacing: CGFloat = 10.0
- public var numberOfRows: Int = 4
- public var textFont: UIFont = UIFont.systemFont(ofSize: 15.0, weight: .bold)
- public var textForeground: UIColor = UIColor.black
- public var textBackground: UIColor = UIColor.yellow
- public var textAlignment: NSTextAlignment = NSTextAlignment.center
- public var textPadding: CGFloat = 20.0
- public var roundedCorners: Bool = true
- public var borderColor: UIColor = UIColor.black
- public var borderWidth: CGFloat = 1.0
- public override init(frame: CGRect) {
- super.init(frame: frame)
- setup()
- }
- required init?(coder aDecoder: NSCoder) {
- fatalError("init(coder:) has not been implemented")
- }
- public func setup() {
- var maxX: CGFloat = 0.0
- var maxY: CGFloat = 0.0
- var totalWidth: CGFloat = 0.0
- var totalHeight: CGFloat = 0.0
- let itemsPerRow = (arrTitles.count/numberOfRows)
- for (index, text) in arrTitles.enumerated() {
- let button = UIButton(type: .custom)
- button.setTitle(text, for: .normal)
- button.setTitleColor(textForeground, for: .normal)
- button.titleLabel?.font = textFont
- button.backgroundColor = textBackground
- button.sizeToFit()
- var width: CGFloat = 60.0
- var height: CGFloat = 0.0
- let currentRow = index/itemsPerRow
- if index >= (currentRow + 1) {
- height = (CGFloat((currentRow)) * verticalSpacing) + (CGFloat((currentRow)) * itemHeight)
- if currentRow != 0 && (index/currentRow) == itemsPerRow && (index % currentRow) == 0 {
- totalWidth = 0.0
- }
- } else {
- height = 0
- if index == 0 {
- totalWidth = 0.0
- }
- }
- if button.frame.width + textPadding > 60.0 {
- width = button.frame.width + textPadding
- }
- let xCoord = CGFloat(totalWidth + horizontalSpacing)
- button.frame = CGRect(x: xCoord, y: height, width: width, height: itemHeight)
- if roundedCorners {
- button.layer.cornerRadius = button.frame.height / 2
- }
- button.layer.borderColor = borderColor.cgColor
- button.layer.borderWidth = borderWidth
- button.layer.masksToBounds = true
- totalWidth = button.frame.maxX + horizontalSpacing
- totalHeight = button.frame.maxY
- if totalWidth > maxX {
- maxX = totalWidth
- }
- if (totalHeight + (2 * verticalSpacing) + itemHeight) > maxY {
- maxY = (totalHeight + (2 * verticalSpacing) + itemHeight)
- }
- self.addSubview(button)
- }
- self.contentSize = CGSize(width: maxX, height: maxY)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement