Skip to content

Commit 0c9ed3a

Browse files
hendesiFelix Desiderato
andauthored
Added fix to cope with custom view issue (#5)
Co-authored-by: Felix Desiderato <felix.desiderato@tum.de>
1 parent 1839280 commit 0c9ed3a

1 file changed

Lines changed: 21 additions & 1 deletion

File tree

Sources/SwiftTooltipKit/Tooltip.swift

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import Foundation
2626
import UIKit
2727

2828
fileprivate let TooltipLayerIdentifier: String = "toolTipID"
29+
fileprivate let margin: CGFloat = 16
2930

3031
open class Tooltip: UIView {
3132

@@ -134,6 +135,8 @@ open class Tooltip: UIView {
134135
}
135136

136137
private func setup() {
138+
translatesAutoresizingMaskIntoConstraints = false
139+
137140
contentView.translatesAutoresizingMaskIntoConstraints = false
138141
self.addSubview(contentView)
139142
contentView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
@@ -150,8 +153,26 @@ open class Tooltip: UIView {
150153
handleAutomaticDismissalIfNedded()
151154
}
152155

156+
/// If the custom view contains a label that has no `preferredMaxLayoutWidth` set, it can happen that its width > screen size width.
157+
/// To prevent that artifically adjust the `preferredMaxLayoutWidth` to stay within bounds.
158+
private func adjustPreferredMaxLayoutWidthIfPossible() {
159+
let labels = contentView.subviews
160+
.compactMap { $0 as? UILabel }
161+
let filterLabels = labels.filter { $0.preferredMaxLayoutWidth == 0 ||
162+
$0.preferredMaxLayoutWidth > UIScreen.main.bounds.width - margin*2 ||
163+
$0.intrinsicContentSize.width > UIScreen.main.bounds.width - margin*2 }
164+
filterLabels.forEach {
165+
$0.preferredMaxLayoutWidth = UIScreen.main.bounds.width - margin*2
166+
}
167+
168+
contentView.setNeedsLayout()
169+
contentView.layoutIfNeeded()
170+
}
171+
153172
/// Computes the original frame of the tooltip.
154173
private func computeFrame() {
174+
adjustPreferredMaxLayoutWidthIfPossible()
175+
155176
let viewSize = contentView.boundsOrIntrinsicContentSize
156177

157178
let origin: CGPoint
@@ -184,7 +205,6 @@ open class Tooltip: UIView {
184205
// Fallback on earlier versions
185206
globlSafeAreasInsets = .zero
186207
}
187-
let margin: CGFloat = 16
188208

189209
precondition(rect.width <= screenBounds.width - margin*2, warningMsg())
190210
precondition(rect.height <= screenBounds.height - margin*2 - globlSafeAreasInsets.top - globlSafeAreasInsets.bottom, warningMsg())

0 commit comments

Comments
 (0)