Strange cornerRadius behaviour on UIView from xib - swift

I created a custom Numpad keyboard through xib and wanted to initialize it with a rounded corners.
Here is the code I use:
import UIKit
class NumpadView: UIView {
#IBOutlet weak var resetButton: NumpadButton!
#IBOutlet weak var decimalButton: NumpadButton!
var target: UITextInput?
var view: UIView?
init(target: UITextInput, view: UIView) {
super.init(frame: .zero)
self.target = target
self.view = view
initializeSubview()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
initializeSubview()
}
func initializeSubview() {
let xibFileName = "NumpadView"
let view = Bundle.main.loadNibNamed(xibFileName, owner: self, options: nil)![0] as! UIView
self.layer.cornerRadius = 30
self.layer.masksToBounds = true
self.addSubview(view)
view.frame = self.bounds
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
But then I receive the strange view look in area where cornerRadius is implemented:
How to remove that grey background which is visible near the rounded corners?
UPDATE:
According to View Debugger it seems like this grey layer between yellow square and Visual Effect View is a UICompatibilityInputViewController:
How I presenting the Numpad:
1.I created a NumpadView as a UIView subclass in a xib:
2.In my VC I just change a standard textField.inputView property on my custom NumpadView:
import UIKit
class NumpadViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
setupKeyboardHide()
textField.delegate = self
textField.inputView = NumpadView(target: textField, view: view)
}
}
Test project on Github

Another option to get your "rounded corners"...
Get rid of the Visual Effect View in your Numpad class, and set a layer mask on the superview at run-time.
In class NumpadView: UIView, UIInputViewAudioFeedback:
override func layoutSubviews() {
super.layoutSubviews()
guard let sv = superview else { return }
let maskLayer = CAShapeLayer()
let bez = UIBezierPath(roundedRect: bounds, cornerRadius: 16)
maskLayer.path = bez.cgPath
sv.layer.mask = maskLayer
}
Looks like this:

Sure, the NumpadView object has rounded corner. However, you are using it like this:
textField.inputView = NumpadView(target: textField, view: view)
So, that part which is not rounded is the textField's inputView. I'm not quite sure if you can modify its layer to have corner radius. But, if you really want to get that rounded corner effect, an easier approach is just to add the NumpadView directly to the parent view and anchored to the bottom. Then show it via the begin editing delegate of the textfield (and hide via end editing).

Related

How to make clickable a part of UIView

I have a custom view with stackview inside. In my stack view contains Image, Label1, and Label2 horizontally.
I set my custom view with constraints with height = 25 and width = 160.
I need to tap only on a specific part of the view. How can I do it?
For example, only Label2 can be clickable.
#IBOutlet weak var label2: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let gesture = UITapGestureRecognizer(target: self, action: #selector(click))
label2.isUserInteractionEnabled = true
label2.addGestureRecognizer(gesture)
}
#objc func click(sender:UITapGestureRecognizer) {
}
You might want to use GestureRecognizers https://developer.apple.com/documentation/uikit/touches_presses_and_gestures

How to give an NSOutlineView a tiled background image that scrolls?

I have a standard NSOutlineView. I would like it to have a background image, which tiles vertically, and which scrolls together with the outline view cells.
I've somewhat achieved this using the following in my ViewController:
class ViewController: NSViewController {
#IBOutlet weak var outlineView: NSOutlineView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let image = NSImage(named: "tile") {
let color = NSColor.init(patternImage: image)
outlineView.backgroundColor = color
}
}
}
That works, except when you scroll past the top or bottom of the view (with the stretch provided by the containing scroll view).
I've tried putting the background image on the scroll view, but then it is static and doesn't scroll with the outline view's content.
I've also tried subclassing various objects in the view hierarchy and overriding their draw(_ dirtyRect: NSRect) method and doing:
self.wantsLayer = true
self.layer?.backgroundColor = ...etc
but got no success from that either.
Can anyone provide any suggestions?
I ended up creating a new custom NSView:
class MyView: NSView {
override func draw(_ dirtyRect: NSRect) {
if let image = NSImage(named: "Tile") {
let color = NSColor.init(patternImage: image)
color.setFill()
dirtyRect.fill()
}
super.draw(dirtyRect)
}
}
Then in my ViewController class I added an instance of the custom view, and used autolayout constraints to pin the new view to my outlineView's clip view starting 2000points above it, and ending 2000 below. This means no matter how far you over-scroll into the stretch area, you still see the tiled background.
class MyViewController: NSViewController {
#IBOutlet weak var outlineView: NSOutlineView!
override func viewDidLoad() {
super.viewDidLoad()
guard let clipView = self.outlineView.superview else { return }
let newView = MyView(frame: .zero) // Frame is set by autolayout below.
newView.translatesAutoresizingMaskIntoConstraints = false
clipView.addSubview(newView, positioned: .below, relativeTo: self.outlineView)
// Add autolayout constraints to pin the new view to the clipView.
// See https://apple.co/3c6EMcH
newView.leadingAnchor.constraint(equalTo: clipView.leadingAnchor).isActive = true
newView.widthAnchor.constraint(equalTo: clipView.widthAnchor).isActive = true
newView.topAnchor.constraint(equalTo: clipView.topAnchor, constant: -2000).isActive = true
newView.bottomAnchor.constraint(equalTo: clipView.bottomAnchor, constant: 2000).isActive = true
}
}
I've removed other code from the above so hopefully I've left everything needed to illustrate the solution.

UIView not resizing from xib file Swift

I have created an xib file with a UIView inside of it. I am using this view inside of my storyboard, and would like it to resize based on the content within it. When I explicitly set the height of the view in the storyboard, it is the same height as the XIB file. Each phone screen seems to have the same xib height and width as well, which causes the view to go off the screen, no matter what I set the constraints to be within the storyboard.
I have tried this to hide the view and set the height of the banner to 35
self.specialistBanner.pillView.isHidden = true
specialistBannerHeight.constant = 35
I have tried
specialistBannerHeight.constant = 35
to get the view to be smaller within the storyboard
I have also tried
self.specialistBanner.sizeToFit()
with no avail
XIB File for the specialist banner view
Label inside the xib file
Pill View within the xib
Storyboard file using the xib view inside of a view controller
class SpecialistBannerView: UIView {
#IBOutlet weak var bannerTitle: UILabel!
#IBOutlet weak var pillView: PillCollectionView!
var viewModel = SpecialistBannerViewModel()
// Initialize xib
let SpecialistBannerView = "SpecialistBannerView"
override func awakeFromNib() {
super.awakeFromNib()
self.translatesAutoresizingMaskIntoConstraints = false
}
override init(frame: CGRect) {
super.init(frame: frame)
initXib(view: self)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initXib(view: self)
}
func initXib(view: SpecialistBannerView) {
let viewToShow = Bundle.main.loadNibNamed(SpecialistBannerView, owner: self, options: nil)?[0] as? UIView ?? UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.sizeToFit()
view.addSubview(viewToShow)
view.frame = view.bounds
view.pillView.setUp()
view.sizeToFit()
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
viewModel.specialistBannerViewProtocol = self
}
Any help would be appreciated
I had your same problem. I found the answer in another question.
You have to override LayoutSubViews() in your custom view and set the bounds
override func layoutSubviews() {
super.layoutSubviews()
// we need to adjust the frame of the subview to no longer match the size used
// in the XIB file BUT the actual frame we got assinged from the superview
self.view.frame = self.bounds
}

Why my background gradient view is not loading in my customer UINavigationController class

I'm trying to set a gradient to the background of my subclassed NavigationController. When I add a colour to the same code it works well but I can't seem to let my gradient show up. I created a subclass of a UIView that returns a CAGradientLayer as its background view.
Here is my subclassed UIView : (Note the colours are weird so I am sure its loading the right Gradient.
#IBDesignable
class GenericBackgrounView: UIView {
override class var layerClass: AnyClass {
return CAGradientLayer.self
}
///The roundness for the corner
#IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet{
setupGradient()
}
}
func setupGradient() {
//let gradientColors = [bgDarkColor.cgColor, bgDarkColor.blended(withFraction: 0.5, of: bgLightColor).cgColor, bgLightColor.cgColor]
let gradientColors = [UIColor.brown.cgColor, UIColor.red.blended(withFraction: 0.5, of: UIColor.cyan).cgColor, UIColor.yellow.cgColor]
gradientLayer.colors = gradientColors
gradientLayer.locations = ESDefault.backgroundGradientColorLocations
setNeedsDisplay()
}
var gradientLayer: CAGradientLayer {
return self.layer as! CAGradientLayer
}
override func awakeFromNib() {
super.awakeFromNib()
setupGradient()
}
override func prepareForInterfaceBuilder() {
setupGradient()
}
}
And Here is my UINavigationController :
class GenericNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
let backView = GenericBackgrounView(frame: self.view.frame)
backView.bounds = self.view.bounds
self.view.backgroundColor = UIColor.clear
self.view.addSubview(backView)
self.view.sendSubview(toBack: backView)
// Do any additional setup after loading the view.
}
}
Also note that my GenericBackgroundView works fine when I use it for any views I add in the interface builder.
I have been at this to long. I think I will suggest to Apple to setup some kind of Theming API in both code and Interface Builder... and the ability to add gradients straight into Interface Builder...
Thanks for you help.
Instead of setting it up in awakeFromNib() , try calling it in viewDidLayoutSubviews(). Reason is that in viewDidLayoutSubviews() will have the correct frame of the view , while in awakeFromNib() you wouldn't know the right frame of the view.From Apple Documentation.
Alright, I've tinkered a bit and found some working code. I would still love to understand the reason why this works and not the way I had it before. I hate feeling it works by magic...
here is the working code : (Remember that my gradient is in form of CAGradientLayer and I have made some static variable that has defaults.
import UIKit
class GenericNavigationController: UINavigationController {
let backViewGradient = Default.testGradientCALayer
override func viewDidLoad() {
super.viewDidLoad()
setupBackground()
}
func setupBackground() {
backViewGradient.frame = self.view.frame
self.view.layer.insertSublayer(backViewGradient, at: 0)
}
override func prepareForInterfaceBuilder() {
setupBackground()
}
}
What I'm wondering is how come since all the UIControls that are subclassed from UIView don't all work the same. They should all have a view that is the background and we should all be able to either add a layer or a subview to them and be able to get my previous code to work or my latest code too which does not work with TableViewCells.
I will leave this question open because I would love to know the truth behind this. I don't think I can fully grasp Swift or Xcode if it behaves somewhat magically and inconsistent.

How to add constraints to a Custom UITableViewCell

I have created a custom cell for my table view and it works fine except that my Image View will not align correctly.
Is there a way to add constraints to a custom cell view? Programmatically or otherwise?
This is what my cell looks like in the storyboard - which is what I was hoping to achieve at run time:
But when I demo the app this is what happens:
Here is another image from the storyboard:
View Controller /w TableView
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
println(questions)
println(finalResults)
let theWidth = view.frame.size.width
let theHeight = view.frame.size.height
tableView.frame = CGRectMake(0,0, theHeight, theWidth)
}
Cell View Controller
override func awakeFromNib() {
let theWidth = UIScreen.mainScreen().bounds.width
contentView.frame = CGRectMake(0,0, theWidth, 64)
answerImage.center = CGPointMake(115, 15)
}
You only have to set up your constraints correctly. Indeed, even if Add Missing Constraints and Reset to Suggested Constraints are handy sometimes they don't know what you want, thus the result cannot always be what you expect.
What you might want to do here is the following.
For you question label set it in center Y of it's container and set it's leading space to the superview. Like so :
Then for you image, you want to set it in center Y of it's container too and set a ratio 1:1 on it. Like so :
Note that you might also want to check the width and height if you don't want your image to upscale (if you set a bigger cell on some device).
You should now have something like that :
And the result :
Let me know if it helped.
PS : I don't have your image so I've just set a background color on the uiimageview
Assuming that you started with a View Controller, Dragged a table and a Cell into the table...
in ViewController: UIViewController...{
#IBOutlet weak var resultsTable: UITableView! // connect to tableView
override func viewDidLoad() {
super.viewDidLoad()
let theWidth = view.frame.size.width
let theHeight = view.frame.size.height
resultsTable.frame = CGRectMake(0,0, theWidth, theHeight)
}
}
in UITableViewCell file:
#IBOutlet weak var imageView: UIImageView!
override func awakeFromNib() {
let theWidth = UIScreen.mainScreen().bounds.width
contentView.frame = CGRectMake(0,0 theWidth, 64)
imageView.center = CGPointMake(115, 15) //mess around with these #
}