Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 如何访问视图控制器中uicollectionviewcell的内容?_Swift_Xcode_Uicollectionview_Uicollectionviewcell - Fatal编程技术网

Swift 如何访问视图控制器中uicollectionviewcell的内容?

Swift 如何访问视图控制器中uicollectionviewcell的内容?,swift,xcode,uicollectionview,uicollectionviewcell,Swift,Xcode,Uicollectionview,Uicollectionviewcell,我正在尝试向UICollectionViewCell内的文本字段添加底部边框,我在我的集合视图所在的视图控制器内注册了该单元格。但是要设置底部边框的大小,我需要设置为它自己的大小,我不知道如何在集合视图单元格中设置,所以我试图将它传递给注册它的视图控制器,但还没有成功 *Obs:我删掉了部分代码,因为它们不相关。 UICollectionViewCell class NameStepCell: UICollectionViewCell { let safeAreaHolder: UIV

我正在尝试向UICollectionViewCell内的文本字段添加底部边框,我在我的集合视图所在的视图控制器内注册了该单元格。但是要设置底部边框的大小,我需要设置为它自己的大小,我不知道如何在集合视图单元格中设置,所以我试图将它传递给注册它的视图控制器,但还没有成功

*Obs:我删掉了部分代码,因为它们不相关。

UICollectionViewCell

class NameStepCell: UICollectionViewCell {

    let safeAreaHolder: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    let title: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0
        label.font = UIFont.boldSystemFont(ofSize: 40)
        label.text = "What is\nyour\nname?"
        return label
    }()

    let txtFieldStack: UIStackView = {
        let stack = UIStackView()
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.alignment = .center
        stack.axis = .horizontal
        stack.distribution = .fillEqually
        stack.spacing = 20
        return stack
    }()

    let nameField: UITextField = {
        let txtFld = UITextField()
        txtFld.keyboardType = UIKeyboardType.default
        txtFld.textContentType = UITextContentType.name
        txtFld.autocapitalizationType = UITextAutocapitalizationType.words
        txtFld.autocorrectionType = .no
        txtFld.textColor = UIColor.black
        return txtFld
    }()

    let lastNameField: UITextField = {
        let txtFld = UITextField()
        txtFld.keyboardType = UIKeyboardType.default
        txtFld.textContentType = UITextContentType.familyName
        txtFld.autocapitalizationType = UITextAutocapitalizationType.words
        txtFld.autocorrectionType = .no
        txtFld.textColor = UIColor.black
        return txtFld
    }()




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

        configuringView()
        configuringTitle()
        configuringTxtField()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func configuringView(){
        addSubview(safeAreaHolder)
        safeAreaHolder.topAnchor.constraint(equalTo: topAnchor).isActive = true
        safeAreaHolder.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16).isActive = true
        safeAreaHolder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        safeAreaHolder.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16).isActive = true
    }

    func configuringTitle(){
        safeAreaHolder.addSubview(title)

        title.topAnchor.constraint(equalTo: safeAreaHolder.topAnchor, constant: 50).isActive = true
        title.trailingAnchor.constraint(equalTo: safeAreaHolder.trailingAnchor).isActive = true
        title.leadingAnchor.constraint(equalTo: safeAreaHolder.leadingAnchor).isActive = true
    }

    func configuringTxtField(){
        safeAreaHolder.addSubview(txtFieldStack)

        txtFieldStack.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 50).isActive = true
        txtFieldStack.trailingAnchor.constraint(equalTo: safeAreaHolder.trailingAnchor).isActive = true
        txtFieldStack.leadingAnchor.constraint(equalTo: safeAreaHolder.leadingAnchor).isActive = true


        txtFieldStack.addArrangedSubview(nameField)
        txtFieldStack.addArrangedSubview(lastNameField)


        nameField.heightAnchor.constraint(equalToConstant: 45).isActive = true
        lastNameField.heightAnchor.constraint(equalToConstant: 45).isActive = true

    }
}
UIViewController

class SignupViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource{


    let stepsCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal

        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.backgroundColor = .white
        collectionView.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.never
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isScrollEnabled = false
        return collectionView
    }()


    override func viewDidLoad() {
        super.viewDidLoad()

        stepsCollectionView.dataSource = self
        stepsCollectionView.delegate = self

        stepsCollectionView.register(NameStepCell.self, forCellWithReuseIdentifier: "nameStepId")
        stepsCollectionView.register(GenderStepCell.self, forCellWithReuseIdentifier: "genderStepId")
        stepsCollectionView.register(BirthdayStepCell.self, forCellWithReuseIdentifier: "birthdayStepId")
        stepsCollectionView.register(EmailStepCell.self, forCellWithReuseIdentifier: "emailStepId")
        stepsCollectionView.register(PasswordStepCell.self, forCellWithReuseIdentifier: "passwordStepId")

        view.backgroundColor = .white
        configuringBottomButton()
        configuringStepCollectionView()
    }

    override func viewDidAppear(_ animated: Bool) {

    }


    Here is where I try to get the nameFied to add the border
    override func viewDidLayoutSubviews() {
        NameStepCell().self.nameField.addBottomBorder()
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if indexPath.item == 1 {
            let genderCell = collectionView.dequeueReusableCell(withReuseIdentifier: "genderStepId", for: indexPath)
            return genderCell
        }else if indexPath.item == 2{
            let birthdayCell = collectionView.dequeueReusableCell(withReuseIdentifier: "birthdayStepId", for: indexPath)
            return birthdayCell
        }else if indexPath.item == 3{
            let emailCell = collectionView.dequeueReusableCell(withReuseIdentifier: "emailStepId", for: indexPath)
            return emailCell
        }else if indexPath.item == 4{
            let passwordCell = collectionView.dequeueReusableCell(withReuseIdentifier: "passwordStepId", for: indexPath)
            return passwordCell
        }

        let nameCell = collectionView.dequeueReusableCell(withReuseIdentifier: "nameStepId", for: indexPath)
        return nameCell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: stepsCollectionView.frame.size.width, height: stepsCollectionView.frame.size.height)
    }
}
extension UITextField {
    func addBottomBorder() {
        let border = CALayer()
        border.frame = CGRect(x: 0, y: 32, width: self.frame.size.width, height: 1)
        border.cornerRadius = 2
        border.masksToBounds = true
        border.backgroundColor = UIColor.init(red: 112/255, green: 112/255, blue: 112/255, alpha: 1).cgColor
        self.layer.masksToBounds = true
        self.layer.addSublayer(border)
    }
}
扩展文本字段以添加底部边框

class SignupViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource{


    let stepsCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal

        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.backgroundColor = .white
        collectionView.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.never
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isScrollEnabled = false
        return collectionView
    }()


    override func viewDidLoad() {
        super.viewDidLoad()

        stepsCollectionView.dataSource = self
        stepsCollectionView.delegate = self

        stepsCollectionView.register(NameStepCell.self, forCellWithReuseIdentifier: "nameStepId")
        stepsCollectionView.register(GenderStepCell.self, forCellWithReuseIdentifier: "genderStepId")
        stepsCollectionView.register(BirthdayStepCell.self, forCellWithReuseIdentifier: "birthdayStepId")
        stepsCollectionView.register(EmailStepCell.self, forCellWithReuseIdentifier: "emailStepId")
        stepsCollectionView.register(PasswordStepCell.self, forCellWithReuseIdentifier: "passwordStepId")

        view.backgroundColor = .white
        configuringBottomButton()
        configuringStepCollectionView()
    }

    override func viewDidAppear(_ animated: Bool) {

    }


    Here is where I try to get the nameFied to add the border
    override func viewDidLayoutSubviews() {
        NameStepCell().self.nameField.addBottomBorder()
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if indexPath.item == 1 {
            let genderCell = collectionView.dequeueReusableCell(withReuseIdentifier: "genderStepId", for: indexPath)
            return genderCell
        }else if indexPath.item == 2{
            let birthdayCell = collectionView.dequeueReusableCell(withReuseIdentifier: "birthdayStepId", for: indexPath)
            return birthdayCell
        }else if indexPath.item == 3{
            let emailCell = collectionView.dequeueReusableCell(withReuseIdentifier: "emailStepId", for: indexPath)
            return emailCell
        }else if indexPath.item == 4{
            let passwordCell = collectionView.dequeueReusableCell(withReuseIdentifier: "passwordStepId", for: indexPath)
            return passwordCell
        }

        let nameCell = collectionView.dequeueReusableCell(withReuseIdentifier: "nameStepId", for: indexPath)
        return nameCell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: stepsCollectionView.frame.size.width, height: stepsCollectionView.frame.size.height)
    }
}
extension UITextField {
    func addBottomBorder() {
        let border = CALayer()
        border.frame = CGRect(x: 0, y: 32, width: self.frame.size.width, height: 1)
        border.cornerRadius = 2
        border.masksToBounds = true
        border.backgroundColor = UIColor.init(red: 112/255, green: 112/255, blue: 112/255, alpha: 1).cgColor
        self.layer.masksToBounds = true
        self.layer.addSublayer(border)
    }
}

您可以尝试以下方法,而不是在viewDidLayoutSubviews中调用addBottomBar()

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if indexPath.item == 1 {
        let genderCell = collectionView.dequeueReusableCell(withReuseIdentifier: "genderStepId", for: indexPath)
        return genderCell
    }else if indexPath.item == 2{
        let birthdayCell = collectionView.dequeueReusableCell(withReuseIdentifier: "birthdayStepId", for: indexPath)
        return birthdayCell
    }else if indexPath.item == 3{
        let emailCell = collectionView.dequeueReusableCell(withReuseIdentifier: "emailStepId", for: indexPath)
        return emailCell
    }else if indexPath.item == 4{
        let passwordCell = collectionView.dequeueReusableCell(withReuseIdentifier: "passwordStepId", for: indexPath)
        return passwordCell
    }

    // Dequeue your NameStepCell from collection view
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "nameStepId", for: indexPath)
    if let nameCell = cell as? NameStepCell {
        // Add bottom border to it right here and return it
        nameCell.nameField.addBottomBorder()
        return nameCell
    }
    return cell
}
编辑:

现在,您无需更改注册视图控制器中的任何内容。请用以下代码替换您的NameStepCell

class NameStepCell: UICollectionViewCell {
    var safeAreaHolder: UIView!
    var title: UILabel!
    var txtFieldStack: UIStackView!
    var nameField: UITextField!
    var lastNameField: UITextField!

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

        configuringView()
        configuringTitle()
        configuringTxtField()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

private extension NameStepCell {
    func configuringView(){
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        self.safeAreaHolder = view

        addSubview(safeAreaHolder)
        safeAreaHolder.topAnchor.constraint(equalTo: topAnchor).isActive = true
        safeAreaHolder.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16).isActive = true
        safeAreaHolder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        safeAreaHolder.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16).isActive = true
        self.safeAreaHolder.layoutIfNeeded()
    }

    func configuringTitle(){
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0
        label.font = UIFont.boldSystemFont(ofSize: 40)
        label.text = "What is\nyour\nname?"
        self.title = label

        safeAreaHolder.addSubview(title)
        title.topAnchor.constraint(equalTo: safeAreaHolder.topAnchor, constant: 50).isActive = true
        title.trailingAnchor.constraint(equalTo: safeAreaHolder.trailingAnchor).isActive = true
        title.leadingAnchor.constraint(equalTo: safeAreaHolder.leadingAnchor).isActive = true
        self.title.layoutIfNeeded()
    }

    func configuringTxtField(){
        let stack = UIStackView()
        stack.backgroundColor = .lightGray
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.alignment = .center
        stack.axis = .horizontal
        stack.distribution = .fillEqually
        stack.spacing = 20
        self.txtFieldStack = stack

        safeAreaHolder.addSubview(txtFieldStack)

        txtFieldStack.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 50).isActive = true
        txtFieldStack.trailingAnchor.constraint(equalTo: safeAreaHolder.trailingAnchor).isActive = true
        txtFieldStack.leadingAnchor.constraint(equalTo: safeAreaHolder.leadingAnchor).isActive = true
        self.txtFieldStack.layoutIfNeeded()

        self.nameField = getTextField(.name)
        self.lastNameField = getTextField(.familyName)

        txtFieldStack.addArrangedSubview(nameField)
        txtFieldStack.addArrangedSubview(lastNameField)

        nameField.heightAnchor.constraint(equalToConstant: 45).isActive = true
        lastNameField.heightAnchor.constraint(equalToConstant: 45).isActive = true

        // After adding constraints, you should call 'layoutIfNeeded()' which recomputes the size and position based on the constraints you've set
        self.nameField.layoutIfNeeded()
        self.lastNameField.layoutIfNeeded()

        self.nameField.addBottomBorder()
        self.lastNameField.addBottomBorder()
    }

    func getTextField(_ textContentType: UITextContentType) -> UITextField {
        let textField = UITextField()
        textField.keyboardType = .default
        textField.textContentType = textContentType
        textField.autocapitalizationType = .words
        textField.autocorrectionType = .no
        textField.textColor = .black
        textField.placeholder = textContentType.rawValue // P.S. Remove placeholder if you don't need. 
        return textField
    }
}

为什么不在创建变量的地方直接使用addBottomBorder扩展名呢。txtFld.addBottomBorder()。它应该可以工作。通常我这样做是为了组织我的代码,但我只是尝试了一下,什么也没发生!它不起作用,什么也没有出现!我获取扩展名中文本字段大小的方式是否有问题?是否在NameStepCell中添加了约束或将frame设置为大小和位置nameField?否,我没有!我在这里测试了一个东西,当我试图通过使用“nameCell.nameField.frame.size.width”获取文本字段的宽度时,它返回0。这有可能是问题所在吗???是的。您需要使用类似于let-txtFld=UITextField(frame:CGRect(x:50,y:50,width:100,height:100))的内容来代替let-txtFld=UITextField()。或者您应该使用约束来调整名称中文本字段的大小和位置。我对上面的内容理解错误,我使用约束,我的名称字段位于堆栈视图中,它固定在边框上。