Set frame of view once - swift

Some of the frames of my views can be set only after layoutSubviews has been called:
class CustomButton: UIButton {
let border = CAShapeLayer()
init() {
super.init(frame: CGRectZero)
border.fillColor = UIColor.whiteColor().CGColor
layer.insertSublayer(border, atIndex: 0)
}
override func layoutSubviews() {
super.layoutSubviews()
border.frame = layer.bounds
border.path = UIBezierPath(rect: bounds).CGPath
}
}
Because I want to animate border in a later state, I only want the code in layoutSubviews to be called once. To do that, I use the following code:
var initial = true
override func layoutSubviews() {
super.layoutSubviews()
if initial {
border.frame = layer.bounds
border.path = UIBezierPath(rect: bounds).CGPath
initial = false
}
}
Question:
I was wondering if there is a better way of doing this. A more elegant and functional way, without having to use an extra variable.

There is a way to do it without an extra variable (albeit not particularly elegant too) which relies on lazy static properties initialization:
class CustomButton: UIButton {
struct InitBorder {
// The static property definition
static let run: Void = {
border.frame = layer.bounds
border.path = UIBezierPath(rect: bounds).CGPath
}()
}
let border = CAShapeLayer()
init() {
super.init(frame: CGRectZero)
border.fillColor = UIColor.whiteColor().CGColor
layer.insertSublayer(border, atIndex: 0)
}
override func layoutSubviews() {
super.layoutSubviews()
// The call which initializes the static property
let _ = InitBorder.run
}
}

let initial = false
override func layoutSubviews() {
super.layoutSubviews()
if initial {
border.frame = layer.bounds
border.path = UIBezierPath(rect: bounds).CGPath
initial = false
}
}

Related

Is there a way to set border to round rectangle that is added to CGMutablePath in Swift?

I am trying to create an overlay view, that has a "cutout" part that comes from a frame that is passed to the view, that size and position of that passed frame will change upon creation of the view. And in that "cutout" part I am expecting to see the content that is under that overlay view. Tried to set border to a rounded rectangle that is added to a CGMutablePath, but no luck.
The expected result is something like this:
The code I currently have in my UIView class, without tried solutions as I can't seem to get them to work properly. This current code displays the expected result, but without the red border:
override func draw(_ rect: CGRect) {
super.draw(rect)
UIColor.blue.setFill()
UIRectFill(rect)
let shapeLayer = CAShapeLayer()
let path = CGMutablePath()
// frame that will change position on the screen
if let frame = changingFrame {
path.addRoundedRect(in: frame, cornerWidth: 16, cornerHeight: 16)
}
path.addRect(bounds)
shapeLayer.path = path
shapeLayer.fillRule = CAShapeLayerFillRule.evenOdd
self.layer.mask = shapeLayer
}
I have tried solutions from here, here, but no luck as CAShapeLayer for border just overlays existing one.
What can I do differently to achieve the expected result? Thanks!
try this ⭐️
If all you want to do is create a rounded rectangle, then you can simply use.
let rectangle = CGRect(x: 0, y: 0, width: 100, height: 100)
let path = UIBezierPath(roundedRect: rectangle, cornerRadius: 20)
view.clipsToBounds = true
view.layer.cornerRadius = 10.0
let border = CAShapeLayer()
border.path = UIBezierPath(roundedRect:view.bounds, cornerRadius:10.0).cgPath
border.frame = view.bounds
border.fillColor = nil
border.strokeColor = UIColor.purple.cgColor
border.lineWidth = borderWidth * 2.0 // doubled since half will be clipped
border.lineDashPattern = [1.0]
view.layer.addSublayer(border)
One approach is to use two sublayers... a "cutout" layer and a "border" layer.
Use the same path for the cutout and the border shape, setting the line width and stroke color for the "outline".
Here's an example -- including making it #IBDesignable with a few #IBInspectable properties:
#IBDesignable
class BorderedCutoutView: UIView {
#IBInspectable
var bkgColor: UIColor = .systemBlue {
didSet {
setNeedsLayout()
}
}
#IBInspectable
var brdColor: UIColor = .white {
didSet {
setNeedsLayout()
}
}
#IBInspectable
var brdWidth: CGFloat = 1 {
didSet {
setNeedsLayout()
}
}
#IBInspectable
var radius: CGFloat = 20 {
didSet {
setNeedsLayout()
}
}
#IBInspectable
var horizInset: CGFloat = 40.0 {
didSet {
setNeedsLayout()
}
}
#IBInspectable
var vertInset: CGFloat = 60.0 {
didSet {
setNeedsLayout()
}
}
private let cutoutLayer = CAShapeLayer()
private let borderLayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
backgroundColor = .clear
}
private func commonInit() -> Void {
backgroundColor = .clear
layer.addSublayer(cutoutLayer)
layer.addSublayer(borderLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
let path = UIBezierPath(rect: bounds)
let cp = UIBezierPath(roundedRect: bounds.insetBy(dx: horizInset, dy: vertInset), cornerRadius: radius)
path.append(cp)
path.usesEvenOddFillRule = true
cutoutLayer.path = path.cgPath
cutoutLayer.fillRule = .evenOdd
cutoutLayer.fillColor = bkgColor.cgColor
borderLayer.path = cp.cgPath
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.lineWidth = brdWidth
borderLayer.strokeColor = brdColor.cgColor
}
}
This example uses horizontal and vertical "inset" values to center the cutout in the view.
Result:

Slider with custom thumb image and text

Hy,
I'm trying to customize a slider by changing the thumb image and add a label over the picture.
For this, in my view in I set the image for slider thumb:
class SliderView: NibLoadingView {
#IBOutlet weak var slider: ThumbTextSlider!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
contentView = legacyLoadXib()
setup()
}
override func setup() {
super.setup()
self.slider.setThumbImage(UIImage(named: "onb_cc_slider_thumb")!, for: .normal)
self.slider.thumbTextLabel.font = UIFont(name: Fonts.SanFranciscoDisplayRegular, size: 14)
}
}
In ThumbTextSlider class I set the text label as below:
class ThumbTextSlider: UISlider {
var thumbTextLabel: UILabel = UILabel()
private var thumbFrame: CGRect {
return thumbRect(forBounds: bounds, trackRect: trackRect(forBounds: bounds), value: value)
}
override func layoutSubviews() {
super.layoutSubviews()
thumbTextLabel.frame = thumbFrame
}
override func awakeFromNib() {
super.awakeFromNib()
addSubview(thumbTextLabel)
thumbTextLabel.layer.zPosition = layer.zPosition + 1
}
}
When I made test the result was a little different.
How, can I fix the issue ?
The expected result:
Kind regards
This class may help you. In class instead of image I created image you can replace with you thumb image.
class ThumbTextSlider: UISlider {
private var thumbTextLabel: UILabel = UILabel()
private var thumbFrame: CGRect {
return thumbRect(forBounds: bounds, trackRect: trackRect(forBounds: bounds), value: value)
}
private lazy var thumbView: UIView = {
let thumb = UIView()
return thumb
}()
override func layoutSubviews() {
super.layoutSubviews()
thumbTextLabel.frame = CGRect(x: thumbFrame.origin.x, y: thumbFrame.origin.y, width: thumbFrame.size.width, height: thumbFrame.size.height)
self.setValue()
}
private func setValue() {
thumbTextLabel.text = self.value.description
}
override func awakeFromNib() {
super.awakeFromNib()
addSubview(thumbTextLabel)
thumbTextLabel.textAlignment = .center
thumbTextLabel.textColor = .blue
thumbTextLabel.adjustsFontSizeToFitWidth = true
thumbTextLabel.layer.zPosition = layer.zPosition + 1
let thumb = thumbImage()
setThumbImage(thumb, for: .normal)
}
private func thumbImage() -> UIImage {
let width = 100
thumbView.frame = CGRect(x: 0, y: 15, width: width, height: 30)
thumbView.layer.cornerRadius = 15
let renderer = UIGraphicsImageRenderer(bounds: thumbView.bounds)
return renderer.image { rendererContext in
rendererContext.cgContext.setShadow(offset: .zero, blur: 5, color: UIColor.black.cgColor)
thumbView.backgroundColor = .red
thumbView.layer.render(in: rendererContext.cgContext)
}
}
override func trackRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(origin: bounds.origin, size: CGSize(width: bounds.width, height: 5))
}
}

UIButton System style selected state, keep image and background

When using the System style of UIButton (nope, i don't want to use the Custom style, as the system provides animations, etc...)
The selected state of system button adds a background and removes the image
This is the Default state
And i want to achieve a selected style like this, where the look when selected is the same as the custom button
ok, finally manged that one out, the key was not to allow the switch to selected state
class ControlButton: UIButton {
var sImage: UIImage?
var dImage: UIImage?
override func awakeFromNib() {
super.awakeFromNib()
sImage = image(for: .selected)
dImage = image(for: .normal)
}
override open var isSelected: Bool {
set {
if newValue {
setImage(sImage, for: .normal)
} else {
setImage(dImage, for: .normal)
}
}
get {
return false
}
}
}
Add this class and set it to your button class
class KButton: UIButton {
var view: UIButton!
#IBInspectable public var textPadding: CGFloat = 5.0 {
didSet {
layoutSubviews()
}
}
#IBInspectable public var circleRadius: CGFloat = 10 {
didSet {
layoutSubviews()
}
}
#IBInspectable public var circleWidth: CGFloat = 2.0 {
didSet {
layoutSubviews()
}
}
#IBInspectable public var currentState: Bool = false {
didSet {
layoutSubviews()
}
}
override func layoutSubviews() {
super.layoutSubviews()
if view != nil {
view?.removeFromSuperview()
}
view = UIButton(frame: CGRect(x: -(self.frame.height) - textPadding, y: 0, width: self.frame.height, height: self.frame.height))
view.backgroundColor = UIColor.clear
let circlePath = UIBezierPath(arcCenter: CGPoint(x: view.frame.height/2, y: view.frame.height/2), radius: circleRadius, startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = self.tintColor.cgColor
shapeLayer.lineWidth = circleWidth
view.layer.addSublayer(shapeLayer)
if currentState {
let circlePath1 = UIBezierPath(arcCenter: CGPoint(x: view.frame.height/2, y: view.frame.height/2), radius: (circleRadius - (circleWidth * 2)), startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: true)
let shapeLayer1 = CAShapeLayer()
shapeLayer1.path = circlePath1.cgPath
shapeLayer1.fillColor = self.tintColor.cgColor
shapeLayer1.strokeColor = self.tintColor.cgColor
shapeLayer1.lineWidth = circleWidth
view.layer.addSublayer(shapeLayer1)
}
self.addSubview(view)
}
}
Then in you click action
#IBAction func buttonClicked(_ sender: KButton) {
sender.currentState = !sender.currentState
}
Make sure to choose the type as KButton

How to set corner radius to a collection of UIButtons

I'm new at using Xcode. My question is regarding "How to set corner.Radius for UIButtons (collection) instead of doing 1 by 1. Once the collection is created i'm using the following line:
self.myButtons.layer.cornerRadius = 10
but that is for a single button. Is it possible to do this for a "collection" of buttons?
enter image description here
any help is greatly appreciated.
#IBOutlet var myButtons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.myButtons.layer.conerRadius = 10
A few options:
Iterate through them yourself:
myButtons.forEach { $0.layer.cornerRadius = 10 }
Use NSArray and its setValue(_:forKey:)
(myButtons as NSArray).setValue(10, forKey: "cornerRadius")
I’d lean towards the former, but the latter is the old Objective-C way of doing it (which is why we had to bridge to NSArray).
The other approach is to define your own UIButton subclass, e.g. RoundedButton that does this for you. Just set the base class for your button in IB to be your custom subclass.
E.g. for fixed corner radius (which you can also adjust right in IB):
#IBDesignable
class RoundedButton: UIButton {
#IBInspectable var cornerRadius: CGFloat = 10 {
didSet {
layer.cornerRadius = cornerRadius
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
override init(frame: CGRect = .zero) {
super.init(frame: frame)
configure()
}
}
private extension RoundedButton {
func configure() {
layer.cornerRadius = cornerRadius
}
}
Or, if you want dynamic rounding based upon the height:
#IBDesignable
class RoundedButton: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
let radius = min(bounds.width, bounds.height) / 2
layer.cornerRadius = radius
}
}
The virtue of this approach is that you can see your rounded buttons rendered right in IB.
Follow this below steps -
1.Choose UIButton from the object library
2.Drag to your storyboard
3.Choose border style as none.
4.Create a Swift file and add this below extension -
extension UIView {
#IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
#IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
#IBInspectable var borderColor: UIColor? {
get {
return UIColor(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.cgColor
}
}
}
extension UIButton {
func roundedButton(){
let maskPAth1 = UIBezierPath(roundedRect: self.bounds,
byRoundingCorners: [.topLeft , .topRight],
cornerRadii:CGSize(width:8.0, height:8.0))
let maskLayer1 = CAShapeLayer()
maskLayer1.frame = self.bounds
maskLayer1.path = maskPAth1.cgPath
self.layer.mask = maskLayer1
}
}
extension UITextField {
func setLeftPaddingPoints(_ amount:CGFloat){
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
self.leftView = paddingView
self.leftViewMode = .always
}
func setRightPaddingPoints(_ amount:CGFloat) {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
self.rightView = paddingView
self.rightViewMode = .always
}
}
extension UITextField {
#IBInspectable var maxLength: Int {
get {
if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
return length
} else {
return Int.max
}
}
set {
objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
}
}
#objc func checkMaxLength(textField: UITextField) {
guard let prospectiveText = self.text,
prospectiveText.count > maxLength
else {
return
}
let selection = selectedTextRange
let indexEndOfText = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
let substring = prospectiveText[..<indexEndOfText]
text = String(substring)
selectedTextRange = selection
}
}
5.Now you can access this extensions either from storyboard or from code to change the values and see the effects.
6.You can change the corner radius, border width, border colour for UIView,UIButton,UITexfield.Try this Method.
Hope this method also helps.
/// Other way to set Corner radius of view; also inspectable from Storyboard.
public extension UIView {
#IBInspectable public var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
// layer.masksToBounds = true
layer.cornerRadius = abs(CGFloat(Int(newValue * 100)) / 100)
}
}}
By usisng this you can set border radius from storyboard
OR
for btn in yourbuttonCollectionName {btn.cornerRadius = 10.0}
You can do this in interface builder. Select your button and then tap the "Identity Inspector" (3rd tab on the right). Under "User Defined Runtime Attributes" hit the plus button. and type layer.conerRadius for the key and 1 for the value. This will set the corner radius by KVO. you can now copy this button or duplicate it with alt+drag and the copies will also have the corner radius (note it doesn't show in the preview window, but it will show at run time).
Alternatively in code:
myButtons.forEach { button in
button.layer.cornerRadius = 1
}
If you are using an outlet collection you can do this in a didSet since that will be called when iOS sets the outlet from the nib file/ storyboard.
extension UIView {
func addCornerRadius(_ radius: CGFloat) {
self.layer.cornerRadius = radius
}
func applyBorder(_ width: CGFloat, borderColor: UIColor) {
self.layer.borderWidth = width
self.layer.borderColor = borderColor.cgColor
}
func addShadow(color: UIColor, opacity: Float, offset: CGSize, radius: CGFloat) {
self.layer.shadowColor = color.cgColor
self.layer.shadowOpacity = opacity
self.layer.shadowOffset = offset
self.layer.shadowRadius = radius
}
func displayToast(message: String) {
let style = CSToastStyle(defaultStyle: ())
style?.backgroundColor = UIColor.black
style?.titleColor = UIColor.white
style?.messageColor = UIColor.white
makeToast(message, duration: 3.0, position: CSToastPositionTop, style: style)
} }
Use As Below :
self.view.addCornerRadius(10)
self.view.addShadow(color: .lightGray, opacity: 1.0, offset: CGSize(width: 1, height: 1), radius: 2)

Preview CAShapeLayer using IBDesignable and IBInspectable

I try to create a view that includes a shape layer, which can be previewed inside Xcode. I somehow do not manage to get it working completely although most of it works. Specifically I cannot figure out how I can set the shape layer's stroke property since it needs to be set before the layer is added otherwise no strokes are rendered. But if I set it before then the inspectable property does not work anymore. Here is how far I came:
import Foundation
import UIKit
#IBDesignable
class CustomView: UIView
{
#IBInspectable var layerBackgroundColor: UIColor? {
didSet {
if let actualColor = layerBackgroundColor {
layer.backgroundColor = actualColor.cgColor
} else {
layerBackgroundColor = nil
}
}
}
#IBInspectable var strokeColor: UIColor? = UIColor.red {
didSet {
if let actualColor = strokeColor {
self.shapeLayer.strokeColor = actualColor.cgColor
} else {
shapeLayer.strokeColor = nil
}
}
}
private var shapeLayer: CAShapeLayer
override func prepareForInterfaceBuilder()
{
let width = self.bounds.width
let height = self.bounds.height
shapeLayer = CAShapeLayer()
shapeLayer.frame = CGRect(x: 0, y: 0, width: width, height: height)
let path = CGMutablePath()
let middle = width/2
path.move(to:CGPoint(x:middle, y:20))
path.addLine(to:CGPoint(x:middle, y:100))
layerBackgroundColor = UIColor.gray
// If this is not set no stroke will be rendered!
strokeColor = UIColor.red
shapeLayer.path = path
shapeLayer.fillColor = nil
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineCap = kCALineCapRound
shapeLayer.lineWidth = 5
layer.addSublayer(shapeLayer)
}
override init(frame: CGRect)
{
shapeLayer = CAShapeLayer()
super.init(frame:frame)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
You are creating a new shapeLayer inside prepareForInterfaceBuilder, so you need to set the color properties of the shapeLayer inside that method. The inspectable variables are being assigned after initialization but before prepareForInterfaceBuilder, so creating a new CAShapeLayer inside prepareForInterfaceBuilder is trashing your previous assignments. I assume in practice you are going to be doing the custom drawing for your class in another method (since this method is never called outside of IB).
Anyway, the following code should fix your problems with IB, I made four changes, all commented....
import Foundation
import UIKit
#IBDesignable
class CustomView: UIView
{
#IBInspectable var layerBackgroundColor: UIColor? {
didSet {
if let actualColor = layerBackgroundColor {
layer.backgroundColor = actualColor.cgColor
} else {
layerBackgroundColor = nil
}
}
}
#IBInspectable var strokeColor: UIColor? {//1 - Maybe you want to comment out assignment to UIColor.red: = UIColor.red {
didSet {
if let actualColor = strokeColor {
self.shapeLayer.strokeColor = actualColor.cgColor
} else {
shapeLayer.strokeColor = nil
}
}
}
private var shapeLayer: CAShapeLayer
override func prepareForInterfaceBuilder()
{
let width = self.bounds.width
let height = self.bounds.height
shapeLayer = CAShapeLayer()
shapeLayer.frame = CGRect(x: 0, y: 0, width: width, height: height)
let path = CGMutablePath()
let middle = width/2
path.move(to:CGPoint(x:middle, y:20))
path.addLine(to:CGPoint(x:middle, y:100))
//2 - you probably also want to set the shapeLayer's background color to the class variable, not hardcode the class variable
//layerBackgroundColor = UIColor.gray
shapeLayer.backgroundColor = layerBackgroundColor?.cgColor
// If this is not set no stroke will be rendered!
//3 Comment the hardcoding line out
//strokeColor = UIColor.red
//4 - assign the shapeLayer's stroke color
shapeLayer.strokeColor = strokeColor?.cgColor
shapeLayer.path = path
shapeLayer.fillColor = nil
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineCap = kCALineCapRound
shapeLayer.lineWidth = 5
layer.addSublayer(shapeLayer)
}
override init(frame: CGRect)
{
shapeLayer = CAShapeLayer()
super.init(frame:frame)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}