简体   繁体   English

在代码中设置“用户定义的运行时属性”

[英]Set “User Defined Runtime Attributes” in code

This may be a silly question but I couldn't find an answer anywhere.这可能是一个愚蠢的问题,但我在任何地方都找不到答案。 If I want to create a UIButton in code and need to set a runtime attribute how would I do so without the interface builder and strictly in code?如果我想在代码中创建一个UIButton并且需要设置一个运行时属性,我将如何在没有界面构建器的情况下并且严格地在代码中这样做?

Actually figured this out, like I said silly question.其实想通了这一点,就像我说的愚蠢的问题。

[UIButton *loginbtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[loginbtn setValue:@"blah" forKey:@"myAttr"];

When you set a runtime attribute in Interface Builder, what you're actually doing is instructing the Nib loading machinery to call the corresponding setter method on that object during Nib loading.当您在 Interface Builder 中设置运行时属性时,您实际上是在指示 Nib 加载机制在 Nib 加载期间调用该对象上的相应 setter 方法。 So, if you have a runtime attribute called for example "name" with a string value of "Bob", all that means is that at some point at runtime during Nib loading, the instance's -setName: method will be called with @"Bob" as the argument.因此,如果您有一个名为“name”的运行时属性,字符串值为“Bob”,这意味着在 Nib 加载期间的某个运行时点,实例的-setName:方法将使用@"Bob"作为论据。

So, to do the same thing at runtime, you just set the property directly, perhaps in your view controller's -viewDidLoad method, or another appropriate place:所以,要在运行时做同样的事情,你只需直接设置属性,也许在你的视图控制器的-viewDidLoad方法中,或者其他合适的地方:

self.button.name = @"Bob";

Wanted to provide an updated answer which leverages Swift property wrappers to cleanly attribute UI elements which should be ignored.想要提供一个更新的答案,它利用 Swift 属性包装器来干净地属性应该被忽略的 UI 元素。

Swift 5.1+ Property Wrapper Swift 5.1+ 属性包装器

@propertyWrapper
public struct HeapIgnore<T> {
    public var wrappedValue: T {
        didSet {
            (wrappedValue as? NSObject)?.setValue(true, forKey: "heapIgnore")
        }
    }

    public init(wrappedValue: T) {
        self.wrappedValue = wrappedValue
    }
}

Example Usage示例用法

... // Inside ViewController
@HeapIgnore
@IBOutlet private var passwordTextField: UITextField!

I've implemented this solution and confirmed in both the Live View and Events Visualizer that Heap ignores events generated by UI elements attributed with the property wrapper.我已经实现了这个解决方案,并在 Live View 和 Events Visualizer 中确认 Heap 会忽略由属性包装器属性的 UI 元素生成的事件。

You need to reference somehow the UIButton in the code (usually by creating an IBOutlet) and then you can access its properties as you would do when you create a button programmatically.您需要以某种方式在代码中引用 UIButton(通常通过创建 IBOutlet),然后您可以像以编程方式创建按钮一样访问其属性。

If you want to create the button programmatically for instance:例如,如果要以编程方式创建按钮:

    UIButton *button = [[UIButton alloc] initWithFrame:frame];
    [button setTitle:@"Title" forState:UIControlStateNormal];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM