JXSegmentedIndicatorImageView.swift 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // JXSegmentedIndicatorImageView.swift
  3. // JXSegmentedView
  4. //
  5. // Created by jiaxin on 2019/1/2.
  6. // Copyright © 2019 jiaxin. All rights reserved.
  7. //
  8. import UIKit
  9. open class JXSegmentedIndicatorImageView: JXSegmentedIndicatorBaseView {
  10. open var image: UIImage? {
  11. didSet {
  12. layer.contents = image?.cgImage
  13. }
  14. }
  15. open override func commonInit() {
  16. super.commonInit()
  17. indicatorWidth = 20
  18. indicatorHeight = 20
  19. layer.contentsGravity = .resizeAspect
  20. }
  21. open override func refreshIndicatorState(model: JXSegmentedIndicatorParamsModel) {
  22. super.refreshIndicatorState(model: model)
  23. backgroundColor = nil
  24. let width = getIndicatorWidth(itemFrame: model.currentSelectedItemFrame)
  25. let height = getIndicatorHeight(itemFrame: model.currentSelectedItemFrame)
  26. let x = model.currentSelectedItemFrame.origin.x + (model.currentSelectedItemFrame.size.width - width)/2
  27. var y = model.currentSelectedItemFrame.size.height - height - verticalOffset
  28. if indicatorPosition == .top {
  29. y = verticalOffset
  30. }
  31. frame = CGRect(x: x, y: y, width: width, height: height)
  32. }
  33. open override func contentScrollViewDidScroll(model: JXSegmentedIndicatorParamsModel) {
  34. super.contentScrollViewDidScroll(model: model)
  35. if model.percent == 0 || !isScrollEnabled {
  36. //model.percent等于0时不需要处理,会调用selectItem(model: JXSegmentedIndicatorParamsModel)方法处理
  37. //isScrollEnabled为false不需要处理
  38. return
  39. }
  40. let rightItemFrame = model.rightItemFrame
  41. let leftItemFrame = model.leftItemFrame
  42. let percent = model.percent
  43. let targetWidth = getIndicatorWidth(itemFrame: model.currentSelectedItemFrame)
  44. let leftX = leftItemFrame.origin.x + (leftItemFrame.size.width - targetWidth)/2
  45. let rightX = rightItemFrame.origin.x + (rightItemFrame.size.width - targetWidth)/2
  46. let targetX = JXSegmentedViewTool.interpolate(from: leftX, to: rightX, percent: CGFloat(percent))
  47. self.frame.origin.x = targetX
  48. }
  49. open override func selectItem(model: JXSegmentedIndicatorParamsModel) {
  50. super.selectItem(model: model)
  51. let targetWidth = getIndicatorWidth(itemFrame: model.currentSelectedItemFrame)
  52. var toFrame = self.frame
  53. toFrame.origin.x = model.currentSelectedItemFrame.origin.x + (model.currentSelectedItemFrame.size.width - targetWidth)/2
  54. if isScrollEnabled && (model.selectedType == .click || model.selectedType == .code) {
  55. //允许滚动且选中类型是点击或代码选中,才进行动画过渡
  56. UIView.animate(withDuration: scrollAnimationDuration, delay: 0, options: .curveEaseOut, animations: {
  57. self.frame = toFrame
  58. }) { (_) in
  59. }
  60. }else {
  61. frame = toFrame
  62. }
  63. }
  64. }