Label - Tai-Kimura/SwiftJsonUI GitHub Wiki

Label

class: SJUILabel
inherits: UILabel

Platform Support

  • UIKit: Full support (All attributes available)
  • SwiftUI: Full support (All attributes available through DynamicComponent)
  • Jetpack Compose: Full support (Maps to Text composable)
  • Android XML: Maps to com.kotlinjsonui.views.KjuiTextView (custom view with font support)

Attributes for Label

attribute name UIKit SwiftUI Compose XML type in json details remarks
text string NSLocalizedString(text, comment:"") will be set to attributedText
font ⚠️ string Font name for label Compose uses fontWeight; XML: app:kjui_font_name
fontSize float Font size for label XML: android:textSize (sp)
fontColor string NSAttributedStringKey.foregroundColor XML: android:textColor
edgeInset string/array Text padding. Array [top, left, bottom, right] or string "top|left|bottom|right" XML: android:padding
lines integer label.numberOfLines (0 = unlimited) maxLines in Compose; XML: android:maxLines
lineBreakMode string Line break mode: Char, Clip, Word, Head, Middle, Tail XML: android:ellipsize
textAlign string Text alignment: Left, Right, Center XML: android:textAlignment
underline JSON Underline styling. See underline attributes
strikethrough JSON Strikethrough styling. See strikethrough attributes
lineHeightMultiple float Line height multiplier
textShadow string Shadow with color, offset, blur
partialAttributes ✅ Dynamic array Partial text styling. See partialAttributes Dynamic mode only
highlightAttributes ✅ Dynamic JSON Attributes when selected Dynamic mode only
highlightColor ✅ Dynamic string Font color when selected Dynamic mode only
hintAttributes ✅ Dynamic JSON Hint text attributes Dynamic mode only
hintColor ✅ Dynamic string Hint text color Dynamic mode only
autoShrink boolean Auto adjust font size to fit
minimumScaleFactor float Minimum scale when autoShrink is true
onclick string Tap gesture selector Use Button in Compose; XML: android:onClick
linkable ✅ Dynamic boolean Make URLs clickable Dynamic mode only; XML: android:autoLink
hint string Placeholder text when empty XML: android:hint
attribute name data type
in constraint info
type in
json
details remarks
lineStyle - string NSAttributedStringKey.underlineStyle. list is below.
Single: NSUnderlineStyle.styleSingle
Double: NSUnderlineStyle.styleDouble
Thick: NSUnderlineStyle.styleThick
None: NSUnderlineStyle.styleNone
Default is NSUnderlineStyle.styleSingle
color - string NSAttributedStringKey.underlineColor.
lineOffset - string NSAttributedStringKey.baselineOffset.
attribute name data type
in constraint info
type in
json
details remarks
lineStyle - string NSAttributedStringKey.strikethroughStyle. list is below.
Single: NSUnderlineStyle.styleSingle
Double: NSUnderlineStyle.styleDouble
Thick: NSUnderlineStyle.styleThick
None: NSUnderlineStyle.styleNone
Default is NSUnderlineStyle.styleSingle
color - string NSAttributedStringKey.strikethroughColor.
attribute name data type
in constraint info
type in
json
details remarks
font - string Font name for label.
fontSize - float Font size for label.
fontColor - string NSAttributedStringKey.foregroundColor.
lineSpacing - float paragraphStyle.lineSpacing.
lineHeightMultiple - float paragraphStyle.lineHeightMultiple.
lineBreakMode - string label.lineBreakMode. Options are:
Char: NSLineBreakMode.byCharWrapping
Clip: NSLineBreakMode.byClipping
Word: NSLineBreakMode.byWordWrapping
Head: NSLineBreakMode.byTruncatingHead
Middle: NSLineBreakMode.byTruncatingMiddle
Tail: NSLineBreakMode.byTruncatingTail
textAlign - string paragraphStyle.alignment. Options are:
Left: NSTextAlignment.left
Right: NSTextAlignment.right
Center: NSTextAlignment.center
underline - JSON JSON for underline. Available attributes are here
textShadow - string NSAttributedStringKey.shadow. Available keys are:
color: shadowColor (hexstring)
offset: shadowOffset.x for first value and shadowOffset.y for second value (float array)
blur: shadowBlurRadius (float)
range - JSON array attributes above will be applied to range defined here. You can also add onclick event to the text in range.

Using partialAttributes with binding_builder

You can dynamically bind values to partialAttributes ranges using the @{} syntax:

Example 1: Dynamic Range with Data Binding

{
  "type": "Label",
  "id": "price_label",
  "text": "Total: $99.99 (Save 20%)",
  "data": [
    {
      "name": "priceStart",
      "class": "Int",
      "defaultValue": 7
    },
    {
      "name": "priceEnd",
      "class": "Int",
      "defaultValue": 13
    }
  ],
  "partialAttributes": [
    {
      "fontColor": "#FF0000",
      "fontSize": 20,
      "font": "bold",
      "range": ["@{priceStart}", "@{priceEnd}"]
    },
    {
      "fontColor": "#00AA00",
      "fontSize": 14,
      "range": [15, 24]
    }
  ]
}

This generates binding code that updates the range dynamically:

priceLabel?.partialAttributesJSON?[0]["range"][0] = JSON(priceStart)
priceLabel?.partialAttributesJSON?[0]["range"][1] = JSON(priceEnd)

Example 2: Complex Partial Attributes

{
  "type": "Label",
  "id": "terms_label",
  "text": "By clicking agree, you accept our Terms of Service and Privacy Policy",
  "fontSize": 14,
  "fontColor": "#333333",
  "data": [
    {
      "name": "termsStart",
      "class": "Int",
      "defaultValue": 33
    },
    {
      "name": "termsEnd",
      "class": "Int",
      "defaultValue": 49
    },
    {
      "name": "privacyStart",
      "class": "Int",
      "defaultValue": 54
    },
    {
      "name": "privacyEnd",
      "class": "Int",
      "defaultValue": 68
    }
  ],
  "partialAttributes": [
    {
      "fontColor": "#0066CC",
      "underline": {
        "lineStyle": "Single",
        "color": "#0066CC"
      },
      "range": ["@{termsStart}", "@{termsEnd}"],
      "onclick": "openTerms"
    },
    {
      "fontColor": "#0066CC",
      "underline": {
        "lineStyle": "Single",
        "color": "#0066CC"
      },
      "range": ["@{privacyStart}", "@{privacyEnd}"],
      "onclick": "openPrivacy"
    }
  ]
}

Example 3: Highlight Search Results

{
  "type": "Label",
  "id": "search_result_label",
  "text": "Swift is a powerful and intuitive programming language",
  "binding_group": ["search"],
  "data": [
    {
      "name": "searchResultRanges",
      "class": "[Int]",
      "defaultValue": []
    }
  ],
  "partialAttributes": [
    {
      "fontColor": "#FF6600",
      "backgroundColor": "#FFFF00",
      "range": "@{searchResultRanges}"
    }
  ]
}

In your ViewController:

// Update search highlights
_binding.searchResultRanges = [0, 5, 35, 46]  // Highlights "Swift" and "programming"
_binding.invalidateSearch()

Notes on partialAttributes with Binding

  • The range array can contain either static numbers or dynamic bindings using @{}
  • When using @{} in range, the variable should be of type Int or [Int]
  • The binding updates the partialAttributesJSON property, which is then applied when the text is rendered
  • You can mix static and dynamic values in the same partialAttributes array

Properties for Label

Static Properties

open class var viewClass: SJUILabel.Type

This property will be used to decide which class to inflate with createFromJSON method. You should define the view's class on this property when you create classes inherite SJUILabel.

static var defaultLinkColor: UIColor

Default color for links (blue). Used when linkable is true and no color is specified.

static var verticalAdjustmentByFonts: [String:CGFloat]

Font-specific vertical adjustments dictionary for fine-tuning text positioning per font.

Instance Properties

public var hint: String?

Placeholder text displayed when main text is empty. Explanation is in Attributes table.

public var selected: Bool

Selection state that determines which attributes to use (normal or highlighted).

public var attributes: [NSAttributedString.Key:NSObject]!

This property stores label's attributes for normal state. When you want to set attributedText, call applyAttributedText instead of setting attributedText directly.
This property will be used to create attributed text.

public var highlightAttributes: [NSAttributedString.Key:NSObject]!

Attributes used when applyAttributedText is called and the label is selected.

public var hintAttributes: [NSAttributedString.Key:NSObject]?

Text attributes for hint text when hint is displayed.

public var partialAttributesJSON: [JSON]?

JSON-based partial text styling configuration. Stores the partial attributes defined in JSON.

public var linkable: Bool

When this property is true, URLs in the text will be automatically detected and made clickable.

public var touchedURL: URL?

The URL that was touched in linkable text. Available after a link is tapped.

public var linkedRanges: [[String:Any]]

Array of linked text ranges with their associated actions and properties.

public weak var touchDelegate: UIViewTapDelegate?

Delegate for handling touch events on the label.

public weak var linkHandleDelegate: NSObject?

Object to handle link click events when linkable is enabled.

public var padding: UIEdgeInsets

Internal padding for text rendering. Spaces between text and its frame.

Override Properties

override var intrinsicContentSize: CGSize { get }

Content size calculation including padding adjustments.

override var alignmentRectInsets: UIEdgeInsets { get }

Alignment rectangle insets for proper layout alignment.

Functions for Label

Static Methods

public class func createFromJSON(attr: JSON, target: Any, views: inout [String: UIView]) -> SJUILabel

Factory method called when the label is created from JSON file.
Override this method when you create classes inheriting from SJUILabel class.

Instance Methods

open func applyAttributedText(_ text: String!)

Call this method to set attributedText with proper attribute handling.

  • Uses attributes for normal state
  • Uses highlightAttributes when selected is true
  • Uses hintAttributes when text is empty and hint is provided
  • Handles partial attributes from partialAttributesJSON
open func applyLinkableAttributedText(_ text: String!, withColor color: UIColor = defaultLinkColor)

Call this method to set attributedText with automatic link detection and styling.
URLs in the text will be made clickable with the specified color.

func characterIndexAtPoint(_ touchPoint: CGPoint) -> Int?

Returns the character index at the specified touch point. Used for handling touches on specific text ranges.

Override Methods

override func drawText(in rect: CGRect)

Custom text drawing implementation that applies padding and handles special rendering.

override func sizeThatFits(_ size: CGSize) -> CGSize

Size calculation that includes padding in the final size.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?)
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)

Touch handling methods for link detection and tap events.

override func onBeginTap()
override func onEndTap()

Custom touch begin and end handling inherited from SJUIView.

Event Handlers

@objc func onLinkTap(_ sender: UITapGestureRecognizer)

Handles tap events on clickable links when linkable is enabled.

⚠️ **GitHub.com Fallback** ⚠️