xcode :情节提要不反映在 ViewController.swift 中对代码所做的更改



我是iOS开发的新手。

当我在ViewController.swift文件(UITextField或UILable等(中创建任何内容时,它不会显示在main.storyboard(或故事板预览(上。

这是故事板在模拟旁边的外观

模拟正是我想要的样子,但它与故事板完全不同

我使用自动布局创建了一个 UITextField,并通过代码中的出口连接了它并对其进行了编辑,如下所示:

视图控制器中的代码.swift

我只是希望情节提要反映我在代码中所做的更改,并且看起来就像模拟器一样。

情节提要不会在每次加载时运行 VC 的代码,因此无法使在 VC 中编写的代码对情节提要产生影响。

但是,您可以做的是创建自定义视图。

在这种情况下,您希望文本字段在情节提要上看起来不同,因此请尝试创建UITextField子类。如果随后在情节提要中将文本字段的自定义类设置为自定义子类,则其外观将符合您的要求。

以下是执行此操作的方法:

@IBDesignable // this is important as it tells IB that it should draw this view in the storyboard
class MyTextField: UITextField {
override func draw(in rect: CGRect) {
// configure how you want the text field to look here...
}
}

情节提要不反映开发模式的更改,它只会在运行时反映。

您可以创建自定义 UITextField 类,而不是在 UIViewController 类中编写代码。这是代码:-

导入 UIKit

类名称字段:UITextField {

// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
self.backgroundColor = UIColor.clear
self.placeholder = "Enter text here"
self.font = UIFont.systemFont(ofSize: 15)
self.borderStyle = .roundedRect
self.autocorrectionType = .no
self.keyboardType = .default
self.returnKeyType = .default
self.clearButtonMode = .whileEditing
self.contentVerticalAlignment = .center
self.borderStyle = .none

// Set UITextField Border Layer
let layer = CALayer()
let width = CGFloat(2.0)
layer.borderColor = UIColor.darkGray.cgColor
layer.frame = CGRect.init(x: 0, y: self.frame.height-width, width: self.frame.width, height: self.frame.height)
layer.borderWidth = width
self.layer.masksToBounds = true
self.layer.addSublayer(layer)
}

}

一旦您创建了一个自定义 UITextField 类,然后在情节提要中将其名称分配给您的 UITextFile 并运行应用程序。您将根据需要找到代码的效果。

在此处输入图像描述

希望这会对你有所帮助。

最新更新