I use Xcode 15.1.
I create a CustomView to use in my project
class CustomView: UIView {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var childView: UIView!
@IBOutlet weak var buttonView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
dprint("CustomView init frame")
viewInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
dprint("CustomView init coder")
viewInit()
}
func viewInit() {
let xibView = Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)![0] as! UIView
addSubview(xibView)
}
}
So, I try to call this custom view inside my UIVIewController using the code:
let cv = CustomView()
self.view.addSubview(cv)
HelperXib.setCenteredXibContraints(cv, self.view)
struch HelperXib {
static func setCenteredXibContraints(_ sameView:UIView, _ parentView: UIView) {
// for errorView message that show on center, example: AlertNoPixKey
sameView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
sameView.centerXAnchor.constraint(equalTo: parentView.centerXAnchor),
sameView.centerYAnchor.constraint(equalTo: parentView.centerYAnchor),
])
}
}
The view shows perfectly on my screen, then I try to use a code to use my one of my UIView(buttonView) inside the custom view to respond to tap events.
let tap2 = UITapGestureRecognizer(target: self, action: #selector(ChargeEnterDataViewController.redirectToMyKeys(_:)) )
cv.buttonView.addGestureRecognizer(tap2)
cv.buttonView.isUserInteractionEnabled = true
Unfortunatley, there's no response when I click the buttonView UIView on my screen.
How can I make it work?
--- EDIT #1 ---
I find something strange. I try to use
print("cv.frame.size: \(cv.frame.size)")
print("cv.buttonView.frame.size: \(cv.buttonView.frame.size)")
it shows this on Xcode console
cv.frame.size: (0.0, 0.0)
cv.buttonView.frame.size: (240.0, 49.0)
For some reason the cv UIView is getting 0.0 for width and height. Don't know why this is happening. Maybe this could be the reason because the tapGesture is not working.
--- EDIT #2 ---
I use the code
let cv = CustomView()
cv.frame.size.width = UIScreen.main.bounds.width
cv.frame.size.height = UIScreen.main.bounds.height
cv.backgroundColor = .blue
My this is the result
I don't understand why there only my part my view that is being showed.
The is the CustomView in Xib
let cv = CustomView()
self.view.addSubview(cv)
So cv has no size. So all of its subviews are outside its bounds. So they can be seen but they cannot be touched; a view outside is superview's bounds fails hit testing by default.
To help with this, say cv.clipsToBounds = true
. Now you won't even see its subviews until you fix the problem.