当应用程序在模拟器中运行时可以正常运行,但在 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/