【问题标题】:xcode : storyboard does not reflect changes made in code in ViewController.swiftxcode:故事板不反映 ViewController.swift 中代码所做的更改
【发布时间】:2017-12-13 09:56:37
【问题描述】:

我是 iOS 开发新手。

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

this is what the storyboard looks next to the simulation

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

我使用 AutoLayout 创建了一个 UITextField,并通过代码中的插座连接它并对其进行了编辑,如下所示:

the code in ViewController.swift

我只想让故事板反映我在代码中所做的更改,并且看起来就像模拟器一样。

【问题讨论】:

    标签: ios iphone swift xcode uiviewcontroller


    【解决方案1】:

    故事板不会在每次加载时运行您的 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...
        }
    }
    

    【讨论】:

    • 您好,感谢您的回答,但您能否详细解释一下具体如何执行此操作。当我添加您首先编写的代码 sn-p 时,它需要用下划线替换“in”,然后我无法将它连接到情节提要中的 UITextField。我只是不确定我是否理解我必须正确地做些什么。
    • @Nox 你只需要为你的故事板文本字段提供文本字段类。
    • @TusharSharma link 我在那里添加了它,但它仍然没有改变。你能给我举个例子来说明覆盖函数内的代码可能是什么样的吗?谢谢
    【解决方案2】:

    Storyboard 不反映开发模式的变化,它只会在运行时反映。

    您可以创建自定义 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 类,然后在情节提要中将其名称分配给您的 UITextFiled 并运行应用程序。你会找到你想要的代码效果。

    enter image description here

    希望对你有帮助。

    【讨论】:

    • 您好,感谢您的深入解释,它现在完美运行
    • 你的惠康@Nox
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 2012-06-15
    • 2015-10-26
    • 2013-07-04
    • 1970-01-01
    • 2017-06-02
    • 2015-08-20
    相关资源
    最近更新 更多