RGB slider color showing in grayscale instead of in color - swift

I'm making a RGB slider programmatically and I've come across an issue where I can't seem to figure out how to properly show the color of each sliders' values as a UIColor. I've gotten as far as changing the colors in the box, but they come out grayscale and I don't understand why.
View class:
extension UIView {
func colorSlider(tintColor: UIColor) -> UISlider {
let slider = UISlider()
slider.minimumValue = 0
slider.maximumValue = 255
slider.isContinuous = true
slider.tintColor = tintColor
slider.frame.size = CGSize(width: 250, height: 20)
return slider
}
}
class SliderView: UIView {
let stackView: UIStackView
let redColorSlider = UIView().colorSlider(tintColor: .red)
let greenColorSlider = UIView().colorSlider(tintColor: .green)
let blueColorSlider = UIView().colorSlider(tintColor: .blue)
let previewColorButton: UIButton = {
let button = UIButton()
button.frame.size = CGSize(width: 80, height: 100)
return button
}()
override init(frame: CGRect) {
self.stackView = UIStackView(arrangedSubviews: [redColorSlider, greenColorSlider, blueColorSlider])
stackView.distribution = .fillEqually
stackView.spacing = 15
stackView.axis = .vertical
super.init(frame: frame)
setupLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupLayout() {
backgroundColor = .white
addSubview(previewColorButton)
previewColorButton.anchor(left: leftAnchor, paddingLeft: 20, width: 80, height: 100)
previewColorButton.centerY(inView: self)
addSubview(stackView)
stackView.anchor(left: previewColorButton.rightAnchor, paddingLeft: 20, paddingRight: 20, width: 250)
stackView.centerY(inView: self)
}
}
Controller class:
class SliderController: UIViewController {
let sliderView = SliderView()
let step: Float = 0.1
let redLabel = UIView().rgbLabel()
var redValue: CGFloat = 0
let greenLabel = UIView().rgbLabel()
var greenValue: CGFloat = 0
let blueLabel = UIView().rgbLabel()
var blueValue: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
view = sliderView
redLabel.text = "0"
greenLabel.text = "0"
blueLabel.text = "0"
sliderView.previewColorButton.backgroundColor = .blue
sliderView.redColorSlider.addTarget(self, action: #selector(sliderValueChanged(sender:)), for: .valueChanged)
sliderView.greenColorSlider.addTarget(self, action: #selector(sliderValueChanged(sender:)), for: .valueChanged)
sliderView.blueColorSlider.addTarget(self, action: #selector(sliderValueChanged(sender:)), for: .valueChanged)
sliderView.previewColorButton.addTarget(self, action: #selector(sliderValueChanged(sender:)), for: .valueChanged)
let stackView = UIStackView(arrangedSubviews: [redLabel, greenLabel, blueLabel])
stackView.distribution = .fillEqually
stackView.spacing = 5
view.addSubview(stackView)
stackView.anchor(bottom: view.safeAreaLayoutGuide.bottomAnchor)
stackView.centerX(inView: view)
}
#objc func sliderValueChanged(sender: UISlider) {
redValue = CGFloat(round(sender.value / step) * step)
greenValue = CGFloat(round(sender.value / step) * step)
blueValue = CGFloat(round(sender.value / step) * step)
redLabel.text = "\(Int(redValue))"
greenLabel.text = "\(Int(greenValue))"
blueLabel.text = "\(Int(blueValue))"
sliderView.previewColorButton.backgroundColor = UIColor(red: redValue/255, green: greenValue/255, blue: blueValue/255, alpha: 1.0)
}
I've tried separating the slider action function #objc func sliderValueChanged to each individual slider action like so:
#objc func redSliderValueDidChange(sender: UISlider) {
let redSliderValue = round(sender.value / step) * step
redValue = CGFloat(redSliderValue)
redLabel.text = "\(Int(redValue))"
}
#objc func greenSliderValueDidChange(sender: UISlider) {
let greenSliderValue = round(sender.value / step) * step
greenValue = CGFloat(greenSliderValue)
greenLabel.text = "\(Int(greenValue))"
}
#objc func blueSliderValueDidChange(sender: UISlider) {
let blueSliderValue = round(sender.value / step) * step
blueValue = CGFloat(blueSliderValue)
blueLabel.text = "\(Int(blueValue))"
}
This helps so that each color label changes individually, as opposed to what I have above, but the colors don't change.
How it looks currently:
I haven't found any information on how to do this programmatically, so any help is appreciated!

Please check the targets you have added to the slider.
Also, you can replace the following method in your code:
#objc func sliderValueChanged(sender: UISlider)
{
sliderView.previewColorButton.backgroundColor = UIColor(red: CGFloat(redSliderValue/255), green: CGFloat(greenSliderValue/255), blue: CGFloat(blueSliderValue/255), alpha: 1.0)
}

Related

Subclassing UITextField with other UI elements / Swift 5

Hello everyone!)
Need some help!)
I have custom text field with input limit which was in my view controller. If you look below, you will see that my text field has: UIView (underlayer with some borders), two UILabels (name label and counter label), and UITextField inside of UIView. Now I want to make UITextField subclass and configure my text field there with whole UI-es.
MARK: - I working without storyboards, the code only.
The question is, can I implement this in UITextField class?) Or maybe better to use UIView class?)
I experimented and tried to do it in TextField class, but stuck on UIView (underlayer), I can't make it behind my text field. I add a bit of code.)
Have you any ideas how to implement this in right way?)
Thanks for every answer!)
Example
Code...
UIViewController class
import UIKit
class ViewController: UIViewController {
var inputLimitTextField = InputLimitTextField(frame: CGRect(x: 45, y: 200, width: 300, height: 40))
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(inputLimitTextField)
}
}
UITextField class
import UIKit
class InputLimitTextField: UITextField {
var underlayerView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
configureTextField()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureTextField()
}
func configureTextField() {
backgroundColor = .purple
underlayerView.backgroundColor = .red
underlayerView.alpha = 0.5
addSubview(underlayerView)
underlayerView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
underlayerView.topAnchor.constraint(equalTo: self.bottomAnchor),
underlayerView.centerYAnchor.constraint(equalTo: self.centerYAnchor),
underlayerView.centerXAnchor.constraint(equalTo: self.centerXAnchor)
])
}
override func layoutSubviews() {
super.layoutSubviews()
underlayerView.frame = self.bounds
sendSubviewToBack(underlayerView)
}
}
Considering the fact that there is still no answer to my question that would solve this issue… Also, given that using subclasses is a pretty popular practice in programming... I didn't find a specific answer to such a question on the stack. That's why I decided to answer my own question. I hope my approach to solving the problem helps someone in the future...
Code...
UIViewController class...
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
private lazy var inputLimitTextField = InputLimitTextField()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(inputLimitTextField)
inputLimitTextFieldPosition()
}
private func inputLimitTextFieldPosition() {
inputLimitTextField.center.x = self.view.center.x
inputLimitTextField.center.y = self.view.center.y - 100
}
}
UITextField class...
import UIKit
class InputLimitTextField: UITextField, UITextFieldDelegate {
private lazy var nameLabel = UILabel()
private lazy var counterLabel = UILabel()
private let textLayer = CATextLayer()
private let padding = UIEdgeInsets(top: 0.5, left: 10, bottom: 0.5, right: 17)
private let purpleUIColor = UIColor(red: 0.2849253164, green: 0.1806431101, blue: 0.5, alpha: 1.0)
private let purpleCGColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(),
components: [0.2849253164, 0.1806431101, 0.5, 1.0])
private let redUIColor = UIColor(red: 1, green: 0.1806431101, blue: 0.09760022642, alpha: 1)
private let redCGColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(),
components: [ 1, 0.1806431101, 0.09760022642, 1.0])
override init(frame: CGRect) {
super.init(frame: frame)
configureTextField()
configureNameLabel()
configureCunterLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureTextField()
configureNameLabel()
configureCunterLabel()
}
private func configureTextField() {
let screenRect = UIScreen.main.bounds
let screenWidth = screenRect.size.width - 25
let textFieldFrame = CGRect(x: 0, y: 0, width: screenWidth, height: 40)
frame = textFieldFrame
backgroundColor = .clear
textColor = purpleUIColor
font = UIFont(name: "Helvetica", size: 17)
placeholder = "Input limit"
textAlignment = .left
contentVerticalAlignment = .center
clearButtonMode = .always
autocorrectionType = .no
keyboardType = .default
returnKeyType = .done
delegate = self
textLayer.backgroundColor = UIColor.white.cgColor
textLayer.borderColor = purpleCGColor
textLayer.borderWidth = 1.2
textLayer.cornerRadius = 10
textLayer.frame = layer.bounds
layer.insertSublayer(textLayer, at: 0)
layer.shadowColor = .init(gray: 0.5, alpha: 0.5)
layer.shadowOpacity = 0.7
layer.shadowOffset = .init(width: 2, height: 2)
addSubview(nameLabel)
nameLabel.frame = CGRect(x: 12, y: -12, width: 55, height: 16)
addSubview(counterLabel)
counterLabel.frame = CGRect(x: screenWidth - 34, y: 9, width: 22, height: 22)
}
override internal func textRect(forBounds bounds: CGRect) -> CGRect {
let bounds = super.textRect(forBounds: bounds)
return bounds.inset(by: padding)
}
override internal func editingRect(forBounds bounds: CGRect) -> CGRect {
let bounds = super.editingRect(forBounds: bounds)
return bounds.inset(by: padding)
}
override internal func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
let screenRect = UIScreen.main.bounds
let screenWidth = screenRect.size.width - 25
return CGRect(x: screenWidth - 70, y: 0, width: 40, height: 40)
}
private func enableUI() {
self.textLayer.borderColor = redCGColor
self.counterLabel.layer.borderColor = redCGColor
self.counterLabel.textColor = redUIColor
self.textColor = redUIColor
self.nameLabel.layer.borderColor = redCGColor
self.nameLabel.textColor = redUIColor
}
private func disableUI() {
self.textLayer.borderColor = purpleCGColor
self.counterLabel.layer.borderColor = purpleCGColor
self.counterLabel.textColor = purpleUIColor
self.textColor = purpleUIColor
self.nameLabel.layer.borderColor = purpleCGColor
self.nameLabel.textColor = purpleUIColor
}
func firstTenCharsColor(text: String) -> NSMutableAttributedString {
let characterCount = 10
let stringLength = text.utf16.count
let attributedString = NSMutableAttributedString(string: text)
if stringLength >= characterCount {
attributedString.addAttribute(.foregroundColor, value: #colorLiteral( red: 0.2849253164, green: 0.1806431101, blue: 0.5, alpha: 1), range: NSMakeRange(0, characterCount) )
}
return attributedString
}
private func updateUI(inputText: String?) {
guard let textCount = inputText?.count else { return }
guard let text = self.text else { return }
if (textCount <= 10){
self.counterLabel.text = "\(10 - textCount)"
disableUI()
} else if (textCount >= 10) {
self.counterLabel.text = "\(10 - textCount)"
enableUI()
self.attributedText = firstTenCharsColor(text: text)
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = self.text, let textRange = Range(range, in: text) else { return true }
let updatedText = text.replacingCharacters(in: textRange, with: string)
self.updateUI(inputText: updatedText)
return true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
self.textLayer.borderColor = purpleCGColor
self.counterLabel.text = "10"
disableUI()
return true
}
private func configureNameLabel() {
nameLabel.backgroundColor = .white
nameLabel.layer.cornerRadius = 3
nameLabel.layer.borderWidth = 1.2
nameLabel.layer.borderColor = purpleCGColor
nameLabel.layer.masksToBounds = true
nameLabel.font = UIFont(name: "Helvetica", size: 11)
nameLabel.text = "Input limit"
nameLabel.textAlignment = .center
nameLabel.textColor = purpleUIColor
}
private func configureCunterLabel() {
counterLabel.backgroundColor = .white
counterLabel.layer.cornerRadius = 5
counterLabel.layer.borderWidth = 1.2
counterLabel.layer.borderColor = purpleCGColor
counterLabel.layer.masksToBounds = true
counterLabel.font = UIFont(name: "Helvetica", size: 12)
counterLabel.text = "10"
counterLabel.textAlignment = .center
counterLabel.textColor = purpleUIColor
}
}
You can use it for any iPhone...
Stay safe and good luck! :)

iOS UIkit custom segmented buttons

I'm looking to create a view with these buttons. There is a background animation when one of the button touched.
Not sure how to do this.
Is custom segmented buttons the way to go?
I went with custom control
import UIKit
protocol MSegmentedControlDelegate:AnyObject {
func segSelectedIndexChange(to index:Int)
}
class MSegmentedControl: UIControl {
private var buttonTitles:[String]!
private var buttons: [UIButton]!
private var selectorView: UIView!
var textColor:UIColor = .black
var selectorViewColor: UIColor = .white
var selectorTextColor: UIColor = .red
weak var delegate:MSegmentedControlDelegate?
public private(set) var selectedIndex : Int = 0
convenience init(frame:CGRect,buttonTitle:[String]) {
self.init(frame: frame)
self.buttonTitles = buttonTitle
}
override func draw(_ rect: CGRect) {
super.draw(rect)
self.backgroundColor = UIColor.white
updateView()
}
func setButtonTitles(buttonTitles:[String]) {
self.buttonTitles = buttonTitles
self.updateView()
}
func setIndex(index:Int) {
buttons.forEach({ $0.setTitleColor(textColor, for: .normal) })
let button = buttons[index]
selectedIndex = index
button.setTitleColor(selectorTextColor, for: .normal)
let selectorPosition = frame.width/CGFloat(buttonTitles.count) * CGFloat(index)
UIView.animate(withDuration: 0.2) {
self.selectorView.frame.origin.x = selectorPosition
}
}
#objc func buttonAction(sender:UIButton) {
for (buttonIndex, btn) in buttons.enumerated() {
btn.setTitleColor(textColor, for: .normal)
if btn == sender {
let selectorPosition = frame.width/CGFloat(buttonTitles.count) * CGFloat(buttonIndex)
selectedIndex = buttonIndex
delegate?.segSelectedIndexChange(to: selectedIndex)
UIView.animate(withDuration: 0.3) {
self.selectorView.frame.origin.x = selectorPosition
}
btn.setTitleColor(selectorTextColor, for: .normal)
}
}
}
}
//Configuration View
extension MSegmentedControl {
private func updateView() {
createButton()
configSelectorView()
configStackView()
}
private func configStackView() {
let stack = UIStackView(arrangedSubviews: buttons)
stack.axis = .horizontal
stack.alignment = .fill
stack.distribution = .fillEqually
addSubview(stack)
stack.translatesAutoresizingMaskIntoConstraints = false
stack.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
stack.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
stack.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
stack.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}
private func configSelectorView() {
let selectorWidth = frame.width / CGFloat(self.buttonTitles.count)
selectorView = UIView(frame: CGRect(x: 0, y: 8, width: selectorWidth, height: 32))
selectorView.backgroundColor = selectorViewColor
selectorView.layer.cornerRadius = 16
selectorView.layer.opacity = 0.5
addSubview(selectorView)
}
private func createButton() {
buttons = [UIButton]()
buttons.removeAll()
subviews.forEach({$0.removeFromSuperview()})
for buttonTitle in buttonTitles {
let button = UIButton(type: .system)
button.setTitle(buttonTitle, for: .normal)
button.addTarget(self, action:#selector(MSegmentedControl.buttonAction(sender:)), for: .touchUpInside)
button.setTitleColor(textColor, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
buttons.append(button)
}
buttons[0].setTitleColor(selectorTextColor, for: .normal)
}
}
Usage:
private let segControl: MSegmentedControl = {
let segControl = MSegmentedControl(
frame: CGRect(x: 0, y: 240, width: 280, height: 50),
buttonTitle: ["Average","Total","Pending"])
segControl.textColor = M.Colors.greyWhite
segControl.selectorTextColor = .white
return segControl
}()
To access index change event:
Implement the delegate on parent view:
addSubview(segControl)
segControl.delegate = self
Delegate:
func segSelectedIndexChange(to index: Int) {
switch index {
case 0: print("Average")
case 1: print("Total")
case 2: print("Pending")
default: break
}
}
Result:

How to center text in a custom segment controller? Swift

I am making a custom segment controller. I faced into the following problem: the text inside the selectable view is not centered. I would like to find a universal solution so that the text remains in the center of the selected segment, regardless of the number of cells. Please , hellp. Thanks a lot!
Image: Example of problem
Code:
#IBDesignable
class CustomSegmentedCntrl: UIControl {
private var buttons = [UIButton]()
private var selector: UIView!
var selectedSegmentIndex = 0
private var segments = [String]() {
didSet {
updateView()
}
}
#IBInspectable
var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
#IBInspectable
var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
#IBInspectable
var textColor: UIColor = .clear {
didSet {
updateView()
}
}
#IBInspectable
var selectorColor: UIColor = .clear {
didSet {
updateView()
}
}
#IBInspectable
var selectorTextColor: UIColor = .clear {
didSet {
updateView()
}
}
func configure(with segmentButtons:[String]) {
self.segments = segmentButtons
}
func setProperties(borderWidth: CGFloat, borderColor: UIColor, textColor: UIColor, selectorColor: UIColor, selectorTextColor: UIColor) {
self.borderWidth = borderWidth
self.borderColor = borderColor
self.selectorColor = selectorColor
self.textColor = textColor
self.selectorTextColor = selectorTextColor
}
func updateView() {
buttons.removeAll()
subviews.forEach { $0.removeFromSuperview()}
let buttonTitles = segments
for buttonTitle in buttonTitles {
let button = UIButton(type: .system)
button.setTitle(buttonTitle, for: .normal)
button.setTitleColor(textColor, for: .normal)
button.addTarget(self, action: #selector(buttonTapped(button:)), for: .touchUpInside)
buttons.append(button)
}
let selectorWidth = frame.width / CGFloat(buttonTitles.count)
selector = UIView(frame: CGRect(x: 0, y: 0, width: selectorWidth, height: frame.height))
selector.layer.cornerRadius = frame.height/2
selector.backgroundColor = selectorColor
addSubview(selector)
///Stack view constraints
let stackView = UIStackView(arrangedSubviews: buttons)
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .fillProportionally
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
stackView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
stackView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}
override func draw(_ rect: CGRect) {
layer.cornerRadius = frame.height/2
}
#objc func buttonTapped(button: UIButton) {
for (buttonIndex, btn) in buttons.enumerated() {
btn.setTitleColor(textColor, for: .normal)
if btn == button {
print(buttonIndex)
selectedSegmentIndex = buttonIndex
let selectorStartPosition = frame.width/CGFloat(buttons.count) * CGFloat(buttonIndex)
UIView.animate(withDuration: 0.2, animations: {
self.selector.frame.origin.x = selectorStartPosition
})
btn.setTitleColor(selectorTextColor, for: .normal)
}
}
}
}
ViewController is look like this:
//View at the storyboard
#IBOutlet weak var secondSegmentedControll: CustomSegmentedCntrl!
func installSecondCell() {
self.secondSegmentedControll.borderColor = .green
self.secondSegmentedControll.selectorTextColor = .blue
self.secondSegmentedControll.selectorColor = .red
self.secondSegmentedControll.configure(with: ["one", "two", "three", "four"])
self.secondSegmentedControll.borderWidth = 1
}
override func viewDidLoad() {
super.viewDidLoad()
installSecondCell()
}
Solution: Add this: stackView.distribution = .fillEqually to updateView()

How dynamic cell height increase using card view in swift

How to resolve the cell height and based on the text dynamic text
My code:
class NotificationTableViewCell: UITableViewCell {
var notification:Notifications? {
didSet {
guard let notificationList = notification else {return}
if let title = notificationList.title{
titleLabel.text = title
}
if let message = notificationList.Message {
descriptionLabel.text = " \(message) "
}
}
}
let ContentView = UIViewFactory()
.build()
//MARK: - cell title Label
let titleLabel = CustomLabel(text: "")
.changeNumberOfLines(lines: 1)
.buildUI()
//MARK: - cell description Label
let descriptionLabel = CustomLabel(text: "")
.changeTextAlignment(.left)
.changeLineBreakMode(mode: .byWordWrapping)
.changeFont(12)
.buildUI()
//MARK: - Time Label
let timeLabel = CustomLabel(text: "")
.buildUI()
//MARK: - IDPal Logo
let logo : UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "idpal")
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
logo.contentMode = .scaleAspectFit
selectionStyle = .none
setUp()
}
//MARK: - SetUpViews
func setUp() {
addSubview(logo)
addSubview(titleLabel)
addSubview(descriptionLabel)
setUpConstraints()
}
override func layoutSubviews() {
super.layoutSubviews()
let cornerRadius: CGFloat = 10
contentView.clipsToBounds = true
contentView.layer.masksToBounds = false
contentView.layer.shadowColor = UIColor(red: 0.74, green: 0.74, blue: 0.74, alpha: 0.50).cgColor
contentView.layer.cornerRadius = cornerRadius
contentView.backgroundColor = UIColor(red: 1.00, green: 1.00, blue: 1.00, alpha: 1)
contentView.layer.borderWidth = 1.0
contentView.layer.borderColor = UIColor.lightGray.cgColor
contentView.alpha = 1
contentView.frame = contentView.frame.inset(by: UIEdgeInsets(top: 2, left: 0, bottom: 0, right: 0))
//set the values for top,left,bottom,right margins
// let margins = UIEdgeInsets(top: 3, left: 0, bottom: 10, right: 0)
// contentView.frame = contentView.frame.inset(by: margins)
}
func setUpConstraints() {
// containerView.topAnchor.constraint(equalTo:topAnchor).isActive = true
// containerView.leftAnchor.constraint(equalTo:leftAnchor).isActive = true
// containerView.rightAnchor.constraint(equalTo:rightAnchor).isActive = true
// containerView.bottomAnchor.constraint(equalTo:bottomAnchor).isActive = true
//MARK: - IDPal Logo constraints
logo.topAnchor.constraint(equalTo:topAnchor,constant:10).isActive = true
logo.leftAnchor.constraint(equalTo:leftAnchor,constant:14).isActive = true
logo.widthAnchor.constraint(equalToConstant:30).isActive = true
logo.heightAnchor.constraint(equalToConstant:40).isActive = true
//MARK: - titleLabel constraints
titleLabel.topAnchor.constraint(equalTo:logo.topAnchor,constant:0).isActive = true
titleLabel.leftAnchor.constraint(equalTo:logo.rightAnchor,constant:10).isActive = true
titleLabel.rightAnchor.constraint(equalTo:rightAnchor).isActive = true
//MARK: - descriptionLabel constraints
descriptionLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor).isActive = true
descriptionLabel.leftAnchor.constraint(equalTo: titleLabel.leftAnchor).isActive = true
descriptionLabel.bottomAnchor.constraint(equalTo: bottomAnchor,constant:10).isActive = true
descriptionLabel.rightAnchor.constraint(equalTo: titleLabel.rightAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Hear my code can't able to configure if found any suggestion drop here please.
adding the border with it's to be space between contendview but not working for me.
I would like to give shadow effect like card similar to the image in my iOS app
thanks

How do I prevent one UIView from being hidden by another UIView?

I'm creating a custom, reusable segmented controller using UIViews and I'm having a problem with overlapping views. It currently looks like this:
You can see that the blue selector is under the buttons but I want it to sit at the bottom and be four pixels high. To do this, I have:
let numberOfButtons = CGFloat(buttonTitles.count)
let selectorWidth = frame.width / numberOfButtons
let selectorYPosition = frame.height - 3 <--- This cause it to be hidden behind the button
selector = UIView(frame: CGRect(x: 0, y: selectorYPosition, width: selectorWidth, height: 4))
selector.layer.cornerRadius = 0
selector.backgroundColor = selectorColor
addSubview(selector)
bringSubviewToFront(selector) <--- I thought this would work but it does nothing
which results in the selector UIView being hidden behind the segment UIView (I have the Y position set to - 3 so you can see how it's being covered up. I actually want it to be - 4, but that makes it disappear entirely):
I thought using bringSubviewToFront() would bring it in front of the segment UIView but it doesn't seem to do anything. I've looked through Apple View Programming Guide and lots of SO threads but can't find an answer.
Can anybody help me see what I'm missing?
Full code:
class CustomSegmentedControl: UIControl {
var buttons = [UIButton]()
var selector: UIView!
var selectedButtonIndex = 0
var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
var borderColor: UIColor = UIColor.black {
didSet {
layer.borderColor = borderColor.cgColor
}
}
var separatorBorderColor: UIColor = UIColor.lightGray {
didSet {
}
}
var commaSeparatedTitles: String = "" {
didSet {
updateView()
}
}
var textColor: UIColor = .lightGray {
didSet {
updateView()
}
}
var selectorColor: UIColor = .blue {
didSet {
updateView()
}
}
var selectorTextColor: UIColor = .black {
didSet {
updateView()
}
}
func updateView() {
buttons.removeAll()
subviews.forEach { $0.removeFromSuperview() }
// create buttons
let buttonTitles = commaSeparatedTitles.components(separatedBy: ",")
for buttonTitle in buttonTitles {
let button = UIButton(type: .system)
button.setTitle(buttonTitle, for: .normal)
button.setTitleColor(textColor, for: .normal)
button.backgroundColor = UIColor.white
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
buttons.append(button)
}
// make first button selected
buttons[0].setTitleColor(selectorTextColor, for: .normal)
let numberOfButtons = CGFloat(buttonTitles.count)
let selectorWidth = frame.width / numberOfButtons
let selectorYPosition = frame.height - 3
selector = UIView(frame: CGRect(x: 0, y: selectorYPosition, width: selectorWidth, height: 4))
selector.layer.cornerRadius = 0
selector.backgroundColor = selectorColor
addSubview(selector)
bringSubviewToFront(selector)
let stackView = UIStackView(arrangedSubviews: buttons)
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .fillEqually
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
stackView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
stackView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}
#objc func buttonTapped(button: UIButton) {
for (buttonIndex, btn) in buttons.enumerated() {
btn.setTitleColor(textColor, for: .normal)
if btn == button {
let numberOfButtons = CGFloat(buttons.count)
let selectorStartPosition = frame.width / numberOfButtons * CGFloat(buttonIndex)
UIView.animate(withDuration: 0.3, animations: { self.selector.frame.origin.x = selectorStartPosition })
btn.setTitleColor(selectorTextColor, for: .normal)
}
}
sendActions(for: .valueChanged)
}
}
You are covering up your selector with the stackView.
You need to do:
bringSubviewToFront(selector)
after you have added all of the views. Move that line to the bottom of updateView().