「Link実装したいけど、UILabelに付加するのは難しいし…」みたいなことがあったので。
概要
UITextviewをUILabelっぽく使うためのTips。なお、IBDesignable入門からの抜き出し情報。
やること
- IBDesignable対応クラスを用意。
- 使いたいUITextView継承クラスに
@IBDesignbable
を付加。 - 使いたいUITextView継承クラスが特に無い場合は、UITextViewのIBDesignable用クラスを作る。
- UITextViewのエクステンションを作成し、必要なプロパティを追加。
- Padding調整プロパティ
- 行数指定プロパティ
- IBファイル(StoryboardやXib)でUITextViewを配置し、1で作成したクラスをCustomClassに設定。
- 各
Padding
を0に指定。 - Linesを指定。
-
Scrolling Enabled
をfalseに指定。
コード
IBDesinable用UITextView継承クラス
@available(*, unavailable, message: "Only use it at Storybord or Xib. When referring it from their file to Swift file, replace reference class name to inherited class.", renamed: "UITextView")
@IBDesignable final class DesignableTextView: UITextView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
}
UITextViewExtension
extension UITextView {
@available(*, unavailable, message: "Only use it at Storybord or Xib. When referring it from their file to Swift file, replace reference class name to inherited class.", renamed: "textContainerInset.top")
@IBInspectable var topPadding: Float {
get { return Float(self.textContainerInset.top) }
set { textContainerInset.top = CGFloat(newValue) }
}
@available(*, unavailable, message: "Only use it at Storybord or Xib. When referring it from their file to Swift file, replace reference class name to inherited class.", renamed: "textContainerInset.left")
@IBInspectable var leftPadding: Float {
get { return Float(self.textContainerInset.left + 5) }
set { textContainerInset.left = CGFloat(newValue - 5) }
}
@available(*, unavailable, message: "Only use it at Storybord or Xib. When referring it from their file to Swift file, replace reference class name to inherited class.", renamed: "textContainerInset.right")
@IBInspectable var rightPadding: Float {
get { return Float(self.textContainerInset.right + 5) }
set { textContainerInset.right = CGFloat(newValue - 5) }
}
@available(*, unavailable, message: "Only use it at Storybord or Xib. When referring it from their file to Swift file, replace reference class name to inherited class.", renamed: "textContainerInset.bottom")
@IBInspectable var bottomPadding: Float {
get { return -1 * Float(self.textContainerInset.bottom) }
set { textContainerInset.bottom = -1 * CGFloat(newValue) }
}
@available(*, unavailable, message: "Only use it at Storybord or Xib. When referring it from their file to Swift file, replace reference class name to inherited class.", renamed: "textContainer.maximumNumberOfLines")
@IBInspectable var lines: Int {
get { return textContainer.maximumNumberOfLines }
set { textContainer.maximumNumberOfLines = newValue }
}
}
備考
(とくになし)