https://kotlinlang.org logo
#compose-ios
Title
# compose-ios
g

Greg Rami

07/12/2023, 6:20 PM
Hi all, I'm trying to create a custom TextField using
UIKitView
, I'm struggling to understand how to call
setAttributedPlaceholder
with the right parameters. Here's what I have so far:
Copy code
UIKitView(
        background = Color.White,
        factory = {
            val textField = object : UITextField(CGRectMake(0.0, 0.0, 0.0, 0.0)) {
                @ObjCAction
                fun editingChanged() {
                    onValueChange(text?.cleanInput() ?: "")
                }
            }
            val nsAttributedString = NSMutableAttributedString() <- how do I configure this, especially set the text
            textField.setAttributedPlaceholder(nsAttributedString)
        }
)
I can create an
NSMutableAttributedString
and then call
Copy code
addAttribute(
                name = "foregroundColor",
                value = UIColor.redColor,
                range = NSMakeRange(0, 1)
            )
on it. But how do I set the text of the placeholder? The
NSAttributedString
and
NSMutableAttributedString
constructors only take
NSCoder
as an argument 😕
👍 1
r

ribesg

07/13/2023, 9:04 AM
Your actual question is not really related to compose, you might have more luck in #ios for this kind of questions in the future. That said, I wrote thousands of lines of UIKit code for my pure Kotlin iOS app, and here are extensions I have for `NSAttributedString`s:
Copy code
@Suppress("UNCHECKED_CAST")
inline fun NSAttributedString.Companion.create(
    text: String,
    vararg attributes: Pair<NSAttributedStringKey, Any>
): NSAttributedString =
    NSAttributedString.create(
        text,
        attributes.toMap() as Map<Any?, *>
    )

inline fun NSAttributedString.Companion.of(
    vararg strings: NSAttributedString
): NSAttributedString =
    NSMutableAttributedString.create("").apply {
        strings.forEach(::appendAttributedString)
    }
Example use:
Copy code
uiView.statusLabel.attributedText = NSAttributedString.of(
                NSAttributedString.create("Status: "),
                NSAttributedString.create(status, NSForegroundColorAttributeName to UIColor.redColor)
            )
I'm not well versed in Swift, but in general when you're looking at Swift/ObjC documentation and see more constructors than your IDE autocompletes for you in Kotlin, look for
.create(…)
functions
g

Greg Rami

07/13/2023, 6:12 PM
Thank you Gael that worked perfectly! 🙌
19 Views