Skip to content
This repository has been archived by the owner on Jun 17, 2021. It is now read-only.

Commit

Permalink
improved logic around size change callback
Browse files Browse the repository at this point in the history
  • Loading branch information
ilyapuchka committed Apr 4, 2017
1 parent 14b759c commit 266d0fd
Showing 1 changed file with 22 additions and 17 deletions.
39 changes: 22 additions & 17 deletions Sources/ReadMoreTextView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ public class ReadMoreTextView: UITextView {
maximumNumberOfLines = 0
_originalMaximumNumberOfLines = _maximumNumberOfLines
}
cachedIntrinsicContentHeight = nil
setNeedsLayout()
}
}
Expand Down Expand Up @@ -207,6 +208,8 @@ public class ReadMoreTextView: UITextView {
return intrinsicContentSize.height
}

private var cachedIntrinsicContentHeight: CGFloat?

public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
return hitTest(pointInGliphRange: point, event: event) { _ in
guard pointIsInReadMoreOrReadLessTextRange(point: point) != nil else { return nil }
Expand Down Expand Up @@ -246,14 +249,6 @@ public class ReadMoreTextView: UITextView {
private func showLessText() {
if let readMoreText = readMoreText, text.hasSuffix(readMoreText) { return }

let oldHeight = intrinsicContentHeight
defer {
invalidateIntrinsicContentSize()
if intrinsicContentHeight != oldHeight {
onSizeChange(self)
}
}

shouldTrim = true
textContainer.maximumNumberOfLines = maximumNumberOfLines

Expand All @@ -266,19 +261,14 @@ public class ReadMoreTextView: UITextView {

textStorage.replaceCharacters(in: range, with: text)
}

invalidateIntrinsicContentSize()
invokeOnSizeChangeIfNeeded()
}

private func showMoreText() {
if let readLessText = readLessText, text.hasSuffix(readLessText) { return }

let oldHeight = intrinsicContentHeight
defer {
invalidateIntrinsicContentSize()
if intrinsicContentHeight != oldHeight {
onSizeChange(self)
}
}


shouldTrim = false
textContainer.maximumNumberOfLines = 0

Expand All @@ -290,6 +280,21 @@ public class ReadMoreTextView: UITextView {
}
textStorage.replaceCharacters(in: range, with: originalAttributedText)
}

invalidateIntrinsicContentSize()
invokeOnSizeChangeIfNeeded()
}

private func invokeOnSizeChangeIfNeeded() {
if let cachedIntrinsicContentHeight = cachedIntrinsicContentHeight {
if intrinsicContentHeight != cachedIntrinsicContentHeight {
self.cachedIntrinsicContentHeight = intrinsicContentHeight
onSizeChange(self)
}
} else {
self.cachedIntrinsicContentHeight = intrinsicContentHeight
onSizeChange(self)
}
}

private func rangeToReplaceWithReadMoreText() -> NSRange {
Expand Down

0 comments on commit 266d0fd

Please sign in to comment.