Trying to add a UIView
that fills the screen, that works fine. But I also want to add a UIButton
to the bottom of the UIView
, but somehow the UIButton
doesn't show up:
let screenSize: CGRect = UIScreen.main.bounds
let myView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height))
myView.backgroundColor = .systemGray5.withAlphaComponent(0.5)
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: 40)
button.setTitle("Sleeping.. Tap here to wake up!", for: UIControl.State.normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.frame.origin = CGPoint(x:0, y:self.view.frame.size.height - button.frame.size.height - 20)
myView.addSubview(button)
self.view.addSubview(myView)
EDIT from answer:
I get error message on line:
button.bottomAnchor.constraint(equalTo: myView.bottomAnchor, constant: 10).isActive = true
Error message:
libc++abi: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors <NSLayoutYAxisAnchor:0x600002658c40 "UIButton:0x7f8dce6146c0'Sleeping.. Tap here to wa...'.bottom"> and <NSLayoutYAxisAnchor:0x600002658a80 "UIView:0x7f8dce613080.bottom"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'
terminating with uncaught exception of type NSException
CoreSimulator 857.7 - Device: iPhone 14 Pro (1B903119-D288-4E1C-B36B-F8B7A44AA0DE) - Runtime: iOS 16.0 (20A360) - DeviceType: iPhone 14 Pro
(Recorded stack frame)