【问题标题】:Swift 3 extension returning "has no member" errorSwift 3 扩展返回“没有成员”错误
【发布时间】:2017-05-03 06:36:21
【问题描述】:

我创建了一个名为 UnderlinedUITextField 的扩展。我试图在另一个类中的 UITextField 上调用它的唯一函数,带下划线,但我收到错误 'UITextField' 类型的值没有成员'带下划线'。

我遵循了我在网上找到的一个示例,它非常适合他们。我不确定为什么会收到此错误。

下划线UITextField扩展

import UIKit

extension UnderlinedUITextField {

func underlined() {

    let border = CALayer()
    let width = CGFloat(1.0)
    border.borderColor = UIColor.lightGray.cgColor
    border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)
    border.borderWidth = width
    self.layer.addSublayer(border)
    self.layer.masksToBounds = true
}
}

HomeScreenVC

import UIKit

class HomeScreenVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    titleOfArticleTextField.underlined() <- WHERE I GET THE ERROR MESSAGE

}

//MARK: Properties

@IBOutlet weak var titleOfArticleTextField: UITextField!
@IBOutlet weak var authorTextField: UITextField!
@IBOutlet weak var bulletPointTextField: UITextField!
@IBOutlet weak var previewOfImage: UIImageView!
@IBOutlet weak var uploadImage: UIButton!

【问题讨论】:

    标签: ios swift uitextfield extension-methods


    【解决方案1】:

    你的扩展应该是UITextField 而不是UnderlinedUITextField 你想扩展现有的类来拥有一个新的方法。

    【讨论】:

      【解决方案2】:

      看起来UnderlinedUITextField是使用UITextField扩展的控件,所以我猜测变量titleOfArticleTextField的类型应该是UnderlinedUITextField而不是UITextField

      @IBOutlet weak var titleOfArticleTextField: UnderlinedUITextField!  // <-- Check type here
      

      这应该可以修复错误,并找到方法。

      由于您的扩展是为UnderlinedUITextField 定义的,因此使用这种方式,您可以安全地将下划线函数调用到只有UnderlinedUITextField 类型的文本字段,并且它不适用于UITextField 类型。

      【讨论】:

        【解决方案3】:

        你的titleOfArticleTextField是一个普通的UITextField所以它不知道你在UnderlinedUITextField中添加了一个名为underlined的函数

        尝试更改您的扩展名,使其改为扩展 UITextField

        extension UITextField {
        
            func underlined() {
                let border = CALayer()
                let width = CGFloat(1.0)
                border.borderColor = UIColor.lightGray.cgColor
                border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)
                border.borderWidth = width
                self.layer.addSublayer(border)
                self.layer.masksToBounds = true
            }
        }
        

        希望对您有所帮助。

        【讨论】:

          【解决方案4】:

          您的扩展名必须是 UITextField

          因为扩展名表示它扩展了该特定类的功能。现在,如果您想为 UITextField 类添加更多功能,那么您必须创建一个名为 UITextField 的扩展。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多