gpt4 book ai didi

iOS 在 Storyboard上添加设计时文本

转载 作者:行者123 更新时间:2023-11-28 13:13:38 24 4
gpt4 key购买 nike

是否可以在 iOS 8 上为 UILabel(或图像,如果使用 UIImageView)设置设计时文本?如果可以,怎么办?

基本上我需要的是在编译之前不要清空我所有的标签,这样它就不会在从网络加载实际数据之前显示虚拟数据。以编程方式清除所有 socket 的算法并不是真正好的解决方案,因为它是不必要的代码。

最佳答案

您可以尝试子类化您想要具有设计时属性的类。这是 UILabel 的示例:

import UIKit

class UIPrototypeLabel: UILabel {
@IBInspectable var isPrototype: Bool = false

override func awakeFromNib() {
if (isPrototype) {
self.text = "test"
}
}

然后,在 IB 中,您将看到 isPrototype,您可以将其设置为 true 或 false。

如果需要,您还可以在 isPrototype:Bool = false 行中将默认值从 false 更改为 true。您还可以更改 isPrototype 为真时发生的情况。我让它成为文本“测试”,这样我可以在测试时看到反馈,所以你可以将它更改为 nil 或“”或其他任何内容。

您也可以避开 isPrototype bool 并让此类始终重置文本。我只是觉得 IBInspectable 属性很酷,但是如果您只想让这个类始终清除标签文本,那么您只需删除 bool 和检查,每次只删除 self.text=nil。

这种方法的缺点是您需要制作所有标签 UIPrototypeLabel 才能获得此功能。

enter image description here

还有第二种更可怕的方法,它将此功能添加到所有 UILabel,即扩展 UILabel。

import ObjectiveC
import UIKit
// Declare a global var to produce a unique address as the assoc object handle
var AssociatedObjectHandle: UInt8 = 0

extension UILabel {
@IBInspectable var isPrototype:Bool {
get {
var optionalObject:AnyObject? = objc_getAssociatedObject(self, &AssociatedObjectHandle)

if let object:AnyObject = optionalObject {
return object as! Bool
} else {
return false // default value when uninitialized
}
}
set {
objc_setAssociatedObject(self, &AssociatedObjectHandle, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}

public override func awakeFromNib() {
if (isPrototype) {
self.text = "test"
}
}
}

归功于Is there a way to set associated objects in Swift?对于其中的一些代码

关于iOS 在 Storyboard上添加设计时文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30220137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com