Hi all, I'm trying to create a custom TextField us...
# compose-ios
g
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
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
Thank you Gael that worked perfectly! 🙌