ios - 快速自定义 View 操作

标签 ios swift uiviewcontroller

我创建了一个自定义的 View,因为不同的 UIViewController 具有相同的外观。

当我将自定义View 添加到UIViewController 时,它似乎是一片空白。那没关系。重要的是如何为 ImageView 上的不可见 Button 覆盖层创建一个 action?我似乎无法将不可见的 ButtonSent Action 连接到我的 UIViewController

如有任何帮助,我们将不胜感激!

编辑: @Mannopson 我就是这样做的

import UIKit

class BookDetailsView: UIView {

    @IBOutlet var wholeView: UIView!
    @IBOutlet var borderView: UIView!
    @IBOutlet weak var imgBook: UIImageView!
    @IBOutlet weak var txtTitle: UITextField!
    @IBOutlet weak var txtAuthor: UITextField!
    @IBOutlet weak var txtDesc: UITextField!
    @IBOutlet weak var btnUploadPhoto: UIButton!

    //init for custom draw
    override init(frame: CGRect) {
        super.init(frame: frame)
        customInit()
    }

    //init for ib
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        customInit()
//        fatalError("init(coder:) has not been implemented")
    }

    private func customInit(){
        //load xib
        Bundle.main.loadNibNamed("BookDetailsView", owner: self, options: nil)

        //add wholeView as subView
        addSubview(wholeView)

        //auto fit
        wholeView.frame = self.bounds
        wholeView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        borderView.layer.borderWidth = 3
        borderView.layer.cornerRadius = 40
    }

}

最佳答案

尝试这样的事情:

class BookDetailsView: UIView {

@IBOutlet var wholeView: UIView!
@IBOutlet var borderView: UIView!
@IBOutlet weak var imgBook: UIImageView!
@IBOutlet weak var txtTitle: UITextField!
@IBOutlet weak var txtAuthor: UITextField!
@IBOutlet weak var txtDesc: UITextField!
@IBOutlet weak var btnUploadPhoto: UIButton!

}

UIViewControllerviewDidLoad 方法中加载自定义 View :

let customView = Bundle.main.loadNibNamed("YourXIBName", owner: self, options: nil).first as! YourUIViewSubclass

// Customize appearence
customView.btnUploadPhoto.backgroundColor = UIColor.red

// Add an action for this button
customView.btnUploadPhoto.addTarget(self, action: #selector(yourFunctionForUIButton), forControlEvents: .touchUpInside)

self.view.addSubview(customView)

自定义函数:

func yourFunctionForUIButton() { 
}

希望对您有所帮助。这不是您主要问题的答案,只是建议

关于ios - 快速自定义 View 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46763010/

相关文章:

ios - 以下swift代码是什么意思?

ios - 泛型类类型不符合 Any

ios - 我如何从 CoreData 关系设置 UItableView 数据源。

ios - 检查用户是否在 HealthKit 中授权了步骤

ios - Xcode 中奇怪的 promiseKit 6 语法行为

Swift - 如何从 UITableViewCell 转到另一个 UITableViewCell?

ios - 如何删除一个 VC 然后直接添加另一个 VC

ios - 如何使 subview 调整大小为 UIScrollView ContentSize?

ios - 如何使用 SwiftUI 将应用程序应用到 iOS 13 深色模式?

ios - 他们有什么办法可以查看Eclipse IDE等Xcode中的代码吗?