Declaring and Using Custom Attributes in Swift

Declaring and using custom attributes in Swift

If we take the iBook as definitive, there appears to be no developer-facing way of creating arbitrary new attributes in the way you can in Java and .NET. I hope this feature comes in later, but for now, it looks like we're out of luck. If you care about this feature, you should file an enhancement request with Apple (Component: Swift Version: X)

FWIW, there's really not a way to do this in Objective-C either.

Set custom attribute on button

If you need custom properties on a class that doesn't belong to you, subclass it and use the subclass instead.

class MyCoolButton : UIButton {
var myCoolProperty : String = "coolness"
}

And later:

var btn = MyCoolButton( // ...

Create custom NSAttributedString.Key

You can simply create a TextStyle enumeration and set your cases "body, headline, bold, italic, etc" (You can assign any value to them if needed). Then you just need to create a new NSAttributedString key:



enum TextStyle {
case body, headline, bold, italic
}


extension NSAttributedString.Key {
static let textStyle: NSAttributedString.Key = .init("textStyle")
}

Playground Testing

let attributedString = NSMutableAttributedString(string: "Hello Playground")

attributedString.setAttributes([.textStyle: TextStyle.headline], range: NSRange(location: 0, length: 5))

attributedString.enumerateAttributes(in: NSRange(location: 0, length: attributedString.length), options: []) { attributes, range, stop in
print(attributes, range, stop )
print(attributedString.attributedSubstring(from: range))
}

How to set attributes for a custom UI element?

You won't be able to set this property in storyboard.

You can do it in code by creating outlet from your custom class (CalcButton) in storyboard to the class (mostly UIViewController or UIView) which own this controls and in your code you can do it for example in viewDidLoad method:

self.yourCalcButtonOutlet.digit = 2;

Dynamically create objects and set attributes in swift

I think that this is what you want:

@objc(MyClass)
class MyClass : NSObject {
var someProperty = 0
}

let type = NSClassFromString("MyClass") as! NSObject.Type
let instance = type()
instance.setValue(12, forKey: "someProperty")

How do I change the attributes of a UILabel with a custom programmatic UIView [Swift 5]

I would rather add another property for the label:

let label: UILabel = {
let lbl = UILabel()
lbl.text = "--"
return lbl
}()

let viewLeft1: UIStackView = {
let stackView = UIStackView()
// configure other properties of stackView, such as constraints,
// but don't add viewLeft1 to it here
return stackView
}()

And then in the initialiser of the view, where you add viewLeft1 to self, also add label to viewLeft1:

self.addSubview(viewLeft1)
viewLeft1.addArrangedSubview(label)


Related Topics



Leave a reply



Submit