ios - 为什么在 Storyboard中看不到我的自定义 View 的预览?

标签 ios swift xcode

当应用程序在模拟器中运行时可以正常运行,但在 Storyboard 中无法看到预览,为什么?

Swift code:

Simulator and Storyboard:

看不到自定义 View 背景颜色,将 UIButton 对象拖到自定义 View 中时看不到真实位置(x,y)及其背景颜色。

在 Android Studio 中,当您在 layout.xml 文件中添加一个对象(自定义 View )时,您可以自动看到预览,是否可以在 Xcode 中做同样的事情?

最佳答案

长话短说;调用 prepareForInterfaceBuilder

// Call The Custom Setup Here
override func prepareForInterfaceBuilder() {
    setupView()
}

layoutSubviews 中调用也有效,但在运行时被调用多次,prepareForInterfaceBuilder 仅针对可设计更改调用,并且仅用于此目的。

长代码:

@IBDesignable
class CustomView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }

    override func prepareForInterfaceBuilder() {
        setupView()
    }

    func InitChildPosition() {
        var i = 1
        for _view in self.subviews {
            if _view is UIButton {
                _view.center.x = (_view.bounds.width / 2)
                _view.center.y = (_view.bounds.height / 2)
            }

            if _view is UIButton && i == 2 {
                _view.center.x = self.bounds.width - (_view.bounds.width / 2)
                _view.center.y = self.bounds.height - (_view.bounds.height / 2)
                _view.backgroundColor = UIColor.darkGray
            }
            i += 1
        }
    }

    func setupView() {
        self.backgroundColor = UIColor.black

        InitChildPosition()
    }
}

关于ios - 为什么在 Storyboard中看不到我的自定义 View 的预览?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42327855/

相关文章:

ios - 我们在哪里注销在viewDidload中注册的通知?

ios - Swift,来自 AnyObject 的 Self

swift - 类型 'SCNVector3' 的值没有成员 'length'

ios - 尝试将 UIButton 连接到代码时出现 "Object Exit"功能

ios - Google Analytics 不显示某些页面的跟踪

ios - 如何快速隐藏collectionview中的特定单元格

ios - 如何解码BLE特征值?

ios - swift 中的 C 数组内存释放

ios - Obj-C/Swift 项目中的致命陷阱异常

c++ - 在 Mac OS X 上结合 Objective-C 和 C/C++