Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Transform original string through style (TextTransform for Style) #93

Closed
stefanomondino opened this issue Dec 12, 2019 · 2 comments
Closed
Assignees
Milestone

Comments

@stefanomondino
Copy link
Contributor

Sometimes it can be useful to have a Style capable of transforming the string itself.
Our current use case scenario is this one:

  • we are in the middle of development and already have a lot of views with labels. Each label has its custom Style
  • Backend started to send us HTML entities (& instead of & is the most annoying example).
  • Not being able to display HTML entities should be an issue on the UILabel

Another use case scenario is this #91

I believe something like this could work:

Style {
 $0.color = UIColor.black
 $0.transform = { text in
       text.replacingOccurrences(of: "&amp:", with: "&")
     }
}

Or even something more complex like BonMot is doing here

I'll try to put together a PR.

@stefanomondino
Copy link
Contributor Author

Way more difficult than I expected.
Transforming input string is quite easy for simple Style, but for StyleGroup is REALLY hard.
Having the chance to manipulate the string by changing its length messes up with ranges used to detect tags.

@malcommac
Copy link
Owner

It will be available inside the next release.

Custom Text Transforms

Sometimes you want to apply custom text transforms to your string; for example you may want to make some text with a given style uppercased with current locale.
In order to provide custom text transform in Style instances just set one or more TextTransform to your Style's .textTransforms property:

let allRedAndUppercaseStyle = Style({
	$0.font = UIFont.boldSystemFont(ofSize: 16.0)
	$0.color = UIColor.red
	$0.textTransforms = [
		.uppercaseWithLocale(Locale.current)
	]
})

let text = "test".set(style: allRedAndUppercaseStyle) // will become red and uppercased (TEST)

While TextTransform is an enum with a predefined set of transform you can also provide your own function which have a String as source and another String as destination:

let markdownBold = Style({
	$0.font = UIFont.boldSystemFont(ofSize: 16.0)
	$0.color = UIColor.red
	$0.textTransforms = [
		.custom({
			return "**\($0)**"
		})
	]
})

All text transforms are applied in the same ordered you set in textTransform property.

@malcommac malcommac changed the title Transform original string through style Transform original string through style (TextTransform for Style) Dec 21, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants