Created Buttons appear in other scenes within the Game - swift

// Button class
class Button: UIButton {
override init(frame: CGRect){
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(){
backgroundColor = #colorLiteral(red: 0.1215686277, green: 0.01176470611, blue: 0.4235294163, alpha: 1)
layer.cornerRadius = 12
layer.masksToBounds = false
translatesAutoresizingMaskIntoConstraints = false
}
}
// The Class where button object is being created
struct Question {
var Question : String!
var Answers : [String]!
var AnswerNumber : Int!
}
class LevelOne: SKScene {
var button = Button()
var buttons = [Button]()
let Question_met = UILabel(frame: CGRect(x: 0.3, y: 0.3, width: 40, height: 21))
var Questions = [Question]()
var QNumber = Int()
var buttonNames = [""]
var AnsNumber = Int()
let selectors:[Selector] = [#selector(handleButton1), #selector(handleButton2), #selector(handleButton3),#selector(handleButton4)]
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "background")
background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
background.zPosition = 0
self.addChild(background)
questionFunction()
buttonFuction()
pickQuestion()
}
#objc func questionFunction(){
Questions = [Question(Question: "What is a BMW ?", Answers: ["Bat","Cat","Vehicle","Pat"], AnswerNumber: 2),
Question(Question: "What is a Boeing ?", Answers: ["Bat","Aircraft","Cat","Pat"], AnswerNumber: 1),
Question(Question: "What is a Ant ?", Answers: ["Insect","Cat","Insect","Nate"], AnswerNumber: 2),
Question(Question: "What is a Apple ?", Answers: ["Fruit","Cat","bat","Pat"], AnswerNumber: 0),
Question(Question: "Where is london ?", Answers: ["UK","USA","France","Germany"], AnswerNumber: 0),
Question(Question: "Where is New York ?", Answers: ["Canada","USA","France","Germany"], AnswerNumber: 2),
Question(Question: "where is Berlin ?", Answers: ["UK","USA","Italy","Germany "], AnswerNumber: 3),
Question(Question: "Where is Toronto ?", Answers: ["India","Africa","Canada","Norway"], AnswerNumber: 2),
Question(Question: "Where is Rome ?", Answers: ["Japan","China","Italy","Ireland"], AnswerNumber: 2),
Question(Question: "where is Chennai ?", Answers: ["India","Brazil","Swiss","Germany"], AnswerNumber: 0),]
Question_met.frame = CGRect(x: 330, y: 70, width: 200, height: 21)
Question_met.backgroundColor = UIColor.orange
Question_met.textColor = UIColor.white
Question_met.textAlignment = NSTextAlignment.center
Question_met.text = "What caused Global Warming ?"
self.view?.addSubview(Question_met)
}
#objc func buttonFuction(){
let stacView = UIStackView()
stacView.spacing = 12
stacView.distribution = .fillEqually
stacView.axis = .horizontal
stacView.translatesAutoresizingMaskIntoConstraints = false
view!.addSubview(stacView)
buttonNames = ["One","Two","Three","Four"]
for i in 0..<4{
button = Button()
button.setTitle(buttonNames[i], for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
button.addTarget(self, action: selectors[i], for: .touchUpInside)
}
NSLayoutConstraint.activate([stacView.centerXAnchor.constraint(equalTo: view!.centerXAnchor),stacView.centerYAnchor.constraint(equalTo: view!.centerYAnchor),stacView.widthAnchor.constraint(equalToConstant: 350),stacView.heightAnchor.constraint(equalToConstant:70)])
}
#objc func pickQuestion(){
if Questions.count > 0{
QNumber = 0
Question_met.text = Questions[QNumber].Question
AnsNumber = Questions[QNumber].AnswerNumber
for i in 0..<buttons.count{
buttons[i].setTitle(Questions[QNumber].Answers[i], for: .normal)
}
Questions.remove(at: QNumber)
}
else {
print("Done!")
let sceneToMoveTo = Instructions(size: self.size)
sceneToMoveTo.scaleMode = self.scaleMode
let myTransition = SKTransition.fade(withDuration: 0.5)
self.view!.presentScene(sceneToMoveTo, transition: myTransition)
}
}
#objc func handleButton1() {
if AnsNumber == 0 {
pickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
#objc func handleButton2(){
if AnsNumber == 1 {
pickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
#objc func handleButton3(){
if AnsNumber == 2 {
pickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
#objc func handleButton4(){
if AnsNumber == 3 {
pickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
}
I currently developing a game, which contains various levels and menu scenes. The current level created a question label and answer buttons and even after the level is complete and you navigate to another scene the buttons and questions remain on the scene no matter which scene you navigate too.
I was hoping to get a solution to only have the buttons and label to appear on the designated scene and don't appear in other scenes unless stated.
Thank you in advance.

I don't think you understand the ownership model here. The ViewController owns its view. The view owns the SKView and the SKView owns the SKScene. There is a back pointer from the SKScene to its SKView, and you are using that to add a UIKit StakcView to the Scene's parent view. Since UIKit sits on top of the SKScene, your button is always visible. The correct architecture here is that the view should add and manage its own subviews. Whenever it loads a new SKScene it should determine what UI that scene needs and then hide any UI that should no be shown. You can do this by just setting .isHidden on the relevant views.

Related

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:

Trying to create method to access the buttons when pressed on swift?

import UIKit
import SpriteKit
import GameplayKit
struct Question {
var Question : String!
var Answers : [String]!
var AnswerNumber : Int!
}
class LevelOne: SKScene {
var button = Button()
var buttons = [Button]()
let Question_met = UILabel(frame: CGRect(x: 0.3, y: 0.3, width: 40, height: 21))
var Questions = [Question]()
var QNumber = Int()
var buttonNames = [""]
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "background")
background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
background.zPosition = 0
self.addChild(background)
QuestionFunction()
ButtonFuction()
PickQuestion()
}
#objc func QuestionFunction(){
Questions = [Question(Question: "What is a Car ?", Answers: ["Bat","Cat","Vehicle","Pat"], AnswerNumber: 3),
Question(Question: "What is a plane ?", Answers: ["Bat","Aircraft","Cat","Pat"], AnswerNumber: 2),
Question(Question: "What is a ant ?", Answers: ["Bat","Cat","Vegetable","Insect"], AnswerNumber: 4),
Question(Question: "What is a Apple ?", Answers: ["Bat","Cat","Fruit","Pat"], AnswerNumber: 3),]
Question_met.frame = CGRect(x: 330, y: 70, width: 200, height: 21)
Question_met.backgroundColor = UIColor.orange
Question_met.textColor = UIColor.white
Question_met.textAlignment = NSTextAlignment.center
Question_met.text = "What caused Global Warming ?"
self.view?.addSubview(Question_met)
}
#objc func ButtonFuction(){
let stacView = UIStackView()
stacView.spacing = 12
stacView.distribution = .fillEqually
stacView.axis = .horizontal
stacView.translatesAutoresizingMaskIntoConstraints = false
view!.addSubview(stacView)
buttonNames = ["One","Two","Three","Four"]
for name in buttonNames {
button = Button()
button.setTitle(name, for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
}
NSLayoutConstraint.activate([stacView.centerXAnchor.constraint(equalTo: view!.centerXAnchor),stacView.centerYAnchor.constraint(equalTo: view!.centerYAnchor),stacView.widthAnchor.constraint(equalToConstant: 350),stacView.heightAnchor.constraint(equalToConstant:70)])
}
#objc func PickQuestion(){
if Questions.count > 0{
QNumber = 0
Question_met.text = Questions[QNumber].Question
for i in 0..<buttons.count{
buttons[i].setTitle(Questions[QNumber].Answers[i], for: .normal)
}
Questions.remove(at: QNumber)
}
else {
print("Done!")
}
}
#objc func handleButton() {
print("")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
}
I created a quiz based game and programmed my button manually but not sure how to create methods that would handle when the button is pressed.
Not sure entirely what you are asking for so going to state what I think you are asking.
You are simply asking on how to connect a button to action.
You're button is declared button = UIButton() in the loop then the action would be handleButton method declared below.
You can simply do addTarget(:) for the button.
button.addTarget(self, action:#selector(handleButton), for: .touchUpInside)
You can google Swift Classname, i.e. Swift UIButton to determine the methods for that class. For example inside UIButton, we can see there is a method identified as addTarget(_:action:for).
From Apple's Docs:
You connect a button to your action method using the addTarget(_:action:for:) method or by creating a connection in Interface Builder. The signature of an action method takes one of three forms, which are listed in Listing 1. Choose the form that provides the information that you need to respond to the button tap.
Edit:
OP decided to ask how to assign button functionality within a loop. To do this, you need a list of functions aka Selectors that you can reference.
let selectors:[Selector] = [#selector(handleButton1), #selector(handleButton2, #selector(handleButton3)]
for i in 0..<3 {
button.addTarget(self, action: selectors[i], for: .touchUpInside)
}

Button function not handling the event properly when pressed?

struct Question {
var Question : String!
var Answers : [String]!
var AnswerNumber : Int!
}
class LevelOne: SKScene {
var button = Button()
var buttons = [Button]()
let Question_met = UILabel(frame: CGRect(x: 0.3, y: 0.3, width: 40, height: 21))
var Questions = [Question]()
var QNumber = Int()
var buttonNames = [""]
var AnsNumber = Int()
let selectors:[Selector] = [#selector(handleButton1), #selector(handleButton2), #selector(handleButton3),#selector(handleButton4)]
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "background")
background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
background.zPosition = 0
self.addChild(background)
QuestionFunction()
ButtonFuction()
PickQuestion()
}
#objc func QuestionFunction(){
Questions = [Question(Question: "What is a BMW ?", Answers: ["Bat","Cat","Vehicle","Pat"], AnswerNumber: 2),
Question(Question: "What is a Boeing ?", Answers: ["Bat","Aircraft","Cat","Pat"], AnswerNumber: 1),
Question(Question: "What is a Ant ?", Answers: ["Insect","Cat","Insect","Nate"], AnswerNumber: 2),
Question(Question: "What is a Apple ?", Answers: ["Fruit","Cat","bat","Pat"], AnswerNumber: 0),
Question(Question: "Where is london ?", Answers: ["UK","USA","France","Germany"], AnswerNumber: 0),
Question(Question: "Where is New York ?", Answers: ["Canada","USA","France","Germany"], AnswerNumber: 2),
Question(Question: "where is Berlin ?", Answers: ["UK","USA","Italy","Germany "], AnswerNumber: 3),
Question(Question: "Where is Toronto ?", Answers: ["India","Africa","Canada","Norway"], AnswerNumber: 2),
Question(Question: "Where is Rome ?", Answers: ["Japan","China","Italy","Ireland"], AnswerNumber: 2),
Question(Question: "where is Chennai ?", Answers: ["India","Brazil","Swiss","Germany"], AnswerNumber: 0),]
Question_met.frame = CGRect(x: 330, y: 70, width: 200, height: 21)
Question_met.backgroundColor = UIColor.orange
Question_met.textColor = UIColor.white
Question_met.textAlignment = NSTextAlignment.center
Question_met.text = "What caused Global Warming ?"
self.view?.addSubview(Question_met)
}
#objc func ButtonFuction(){
let stacView = UIStackView()
stacView.spacing = 12
stacView.distribution = .fillEqually
stacView.axis = .horizontal
stacView.translatesAutoresizingMaskIntoConstraints = false
view!.addSubview(stacView)
buttonNames = ["One","Two","Three","Four"]
for name in buttonNames {
button = Button()
button.setTitle(name, for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
}
for i in 0..<4{
button.addTarget(self, action: selectors[i], for: .touchUpInside)
}
NSLayoutConstraint.activate([stacView.centerXAnchor.constraint(equalTo: view!.centerXAnchor),stacView.centerYAnchor.constraint(equalTo: view!.centerYAnchor),stacView.widthAnchor.constraint(equalToConstant: 350),stacView.heightAnchor.constraint(equalToConstant:70)])
}
#objc func PickQuestion(){
if Questions.count > 0{
QNumber = 0
Question_met.text = Questions[QNumber].Question
AnsNumber = Questions[QNumber].AnswerNumber
for i in 0..<buttons.count{
buttons[i].setTitle(Questions[QNumber].Answers[i], for: .normal)
}
Questions.remove(at: QNumber)
}
else {
print("Done!")
}
}
#objc func handleButton1() {
if AnsNumber == 0 {
PickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
#objc func handleButton2(){
if AnsNumber == 1 {
PickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
#objc func handleButton3(){
if AnsNumber == 2 {
PickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
#objc func handleButton4(){
if AnsNumber == 3 {
PickQuestion()
print("Correct!")
}
else {
print("You are Wrong!!!")
}
}
}
The button action methods don't seem to be accurate in knowing which right answer button is being pressed while different number is assigned as answer for each question the methods seems to only move forward when pressing the last button.
Thank you in advance much appreciate the help.
Your problem is located in your ButtonFunction():
for name in buttonNames {
button = Button()
button.setTitle(name, for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
}
for i in 0..<4{
button.addTarget(self, action: selectors[i], for: .touchUpInside)
}
In the second loop, you do not initialize the button variable, so this is always the fourth button..
Better join this code in only one loop like so:
for i in 0..<4{
button = Button()
button.setTitle(buttonNames[i], for: .normal)
stacView.addArrangedSubview(button)
buttons.append(button)
button.addTarget(self, action: selectors[i], for: .touchUpInside)
}
Beyond this solution some advices to your coding style:
for convenience and better readability, function names and variable names should start with a lower letter
declare your variables in the smallest possible scope.
button, buttonNames and selectors are only used in ButtonFunction(), so these should be declared there.
declaration of button should in fact be in the for loop only. This way, the compiler would have told you, that button is unknown in your second loop and you would have seen the problem on your own ;)

How to set top left and right corner radius with desired drop shadow in UITabbar?

I've spent almost a couple of hours to figure it out. However, it did not happen and finally, I had to come here. Two things are required to be achieved:
Firstly I'd like to have a spontaneous corner radius at the top (which is basically TopRight & TopLeft) of UITabbar.
Secondly, I'd like to have a shadow above those corner radius(shown in below image).
Please have a look at below image
Let me know if anything further required from my side, I'll surely provide that.
Any help will be appreciated.
Edit 1
One more little question arose here along, suppose, Even if, However, we were able to accomplish this, Would Apple review team accept the application?
I'm being little nervous and curious about it.
Q : One more little question arose here along, suppose, Even if, However, we were able to accomplish this, Would Apple review team accept the application?
A: Yes They are accept your app I have Add This Kind Of TabBar.
Create Custom TabBar
HomeTabController
import UIKit
class HomeTabController: UITabBarController
{
var viewCustomeTab : CustomeTabView!
var lastSender : UIButton!
//MARK:- ViewController Methods
override func viewDidLoad()
{
super.viewDidLoad()
UITabBar.appearance().shadowImage = UIImage()
allocateTabItems()
}
//MARK:- Prepare Methods
// Allocate shop controller with tab bar
func allocateTabItems()
{
let vc1 = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "Avc") as? Avc
let item1 = UINavigationController(rootViewController: vc1!)
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.viewControllers = [item1]
createTabBar()
}
func createTabBar()
{
viewCustomeTab = CustomeTabView.instanceFromNib()
viewCustomeTab.translatesAutoresizingMaskIntoConstraints = false
viewCustomeTab.call()
self.view.addSubview(viewCustomeTab)
if #available(iOS 11, *)
{
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([guide.bottomAnchor.constraint(equalToSystemSpacingBelow: viewCustomeTab.bottomAnchor, multiplier: 0), viewCustomeTab.leadingAnchor.constraint(equalToSystemSpacingAfter: guide.leadingAnchor, multiplier: 0), guide.trailingAnchor.constraint(equalToSystemSpacingAfter: viewCustomeTab.trailingAnchor, multiplier: 0), viewCustomeTab.heightAnchor.constraint(equalToConstant: 70) ])
}
else
{
let standardSpacing: CGFloat = 0
NSLayoutConstraint.activate([viewCustomeTab.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing), bottomLayoutGuide.topAnchor.constraint(equalTo: viewCustomeTab.bottomAnchor, constant: standardSpacing)
])
}
viewCustomeTab.btnTab1.addTarget(self, action: #selector(HomeTabController.buttonTabClickAction(sender:)), for: .touchUpInside)
viewCustomeTab.btnTab2.addTarget(self, action: #selector(HomeTabController.buttonTabClickAction(sender:)), for: .touchUpInside)
viewCustomeTab.btnTab3.addTarget(self, action: #selector(HomeTabController.buttonTabClickAction(sender:)), for: .touchUpInside)
viewCustomeTab.btnTab4.addTarget(self, action: #selector(HomeTabController.buttonTabClickAction(sender:)), for: .touchUpInside)
viewCustomeTab.btnTab5.addTarget(self, action: #selector(HomeTabController.buttonTabClickAction(sender:)), for: .touchUpInside)
//self.view.layoutIfNeeded()
viewCustomeTab.layoutIfNeeded()
viewCustomeTab.btnTab1.alignContentVerticallyByCenter(offset: 3)
viewCustomeTab.btnTab2.alignContentVerticallyByCenter(offset: 3)
viewCustomeTab.btnTab3.alignContentVerticallyByCenter(offset: 3)
viewCustomeTab.btnTab4.alignContentVerticallyByCenter(offset: 3)
viewCustomeTab.btnTab5.alignContentVerticallyByCenter(offset: 3)
viewCustomeTab.btnTab1.isSelected = true
}
//MARK:- Button Click Actions
//Manage Tab From Here
func setSelect(sender:UIButton)
{
viewCustomeTab.btnTab1.isSelected = false
viewCustomeTab.btnTab2.isSelected = false
viewCustomeTab.btnTab3.isSelected = false
viewCustomeTab.btnTab4.isSelected = false
viewCustomeTab.btnTab5.isSelected = false
sender.isSelected = true
}
#objc func buttonTabClickAction(sender:UIButton)
{
//self.selectedIndex = sender.tag
if sender.tag == 0
{
let vc1 = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "Bvc") as? Bvc
let item1 = UINavigationController(rootViewController: vc1!)
item1.navigationBar.isHidden = false
self.viewControllers = [item1]
setSelect(sender: viewCustomeTab.btnTab1)
return
}
if sender.tag == 1
{
let vc2 = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "Cvc") as? Cvc
let item2 = UINavigationController(rootViewController: vc2!)
item2.navigationBar.isHidden = false
item2.navigationBar.isTranslucent = false
self.viewControllers = [item2]
setSelect(sender: viewCustomeTab.btnTab2)
return
}
if sender.tag == 2
{
let vc3 = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "Dvc") as? Dvc
let item3 = UINavigationController(rootViewController: vc3!)
item3.navigationBar.isHidden = false
item3.navigationBar.isTranslucent = false
self.viewControllers = [item3]
setSelect(sender: viewCustomeTab.btnTab3)
return
}
if sender.tag == 3
{
}
if sender.tag == 4
{
}
}
}
Create Custom View For Shadow Effect and For + Button.
import UIKit
class CustomeTabView: UIView
{
#IBOutlet weak var btnTab5: UIButton!
#IBOutlet weak var btnTab4: UIButton!
#IBOutlet weak var btnTab3: UIButton!
#IBOutlet weak var btnTab2: UIButton!
#IBOutlet weak var btnTab1: UIButton!
#IBOutlet weak var vRadius: UIView!
class func instanceFromNib() -> CustomeTabView
{
return UINib(nibName: "CustomeTabView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! CustomeTabView
}
private var shadowLayer: CAShapeLayer!
override func layoutSubviews()
{
super.layoutSubviews()
let shadowSize : CGFloat = 2.0
let shadowPath = UIBezierPath(roundedRect: CGRect(x: -shadowSize / 2, y: -shadowSize / 2, width: self.vRadius.frame.size.width, height: self.vRadius.frame.size.height), cornerRadius : 20)
self.vRadius.layer.masksToBounds = false
self.vRadius.layer.shadowColor = UIColor.black.cgColor
self.vRadius.layer.shadowOffset = CGSize.zero//(width: self.vRadius.frame.size.width, height: self.vRadius.frame.size.height)
self.vRadius.layer.shadowOpacity = 0.5
self.vRadius.layer.shadowPath = shadowPath.cgPath
self.vRadius.layer.cornerRadius = 20
}
OpenImg
Swift 4.2
You can achieve this with some custom view with a custom tab bar controller. You can customize the colors and shadows by editing only the custom views.
Custom Tab Bar Controller
import UIKit
class MainTabBarController: UITabBarController{
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
tabBar.backgroundImage = UIImage.from(color: .clear)
tabBar.shadowImage = UIImage()
let tabbarBackgroundView = RoundShadowView(frame: tabBar.frame)
tabbarBackgroundView.cornerRadius = 25
tabbarBackgroundView.backgroundColor = .white
tabbarBackgroundView.frame = tabBar.frame
view.addSubview(tabbarBackgroundView)
let fillerView = UIView()
fillerView.frame = tabBar.frame
fillerView.roundCorners([.topLeft, .topRight], radius: 25)
fillerView.backgroundColor = .white
view.addSubview(fillerView)
view.bringSubviewToFront(tabBar)
}
Rounded Shadow View
import UIKit
class RoundShadowView: UIView {
let containerView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
layoutView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func layoutView() {
// set the shadow of the view's layer
layer.backgroundColor = UIColor.clear.cgColor
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: -8.0)
layer.shadowOpacity = 0.12
layer.shadowRadius = 10.0
containerView.layer.cornerRadius = cornerRadius
containerView.layer.masksToBounds = true
addSubview(containerView)
containerView.translatesAutoresizingMaskIntoConstraints = false
// pin the containerView to the edges to the view
containerView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
containerView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
containerView.topAnchor.constraint(equalTo: topAnchor).isActive = true
containerView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
}
UIImage extension
import UIKit
extension UIImage {
static func from(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
To add any radius or shape you can use a UIBezierPath. The example that I put has left and right corners with a radius and you can use more designable personalizations if you want.
#IBDesignable class TabBarWithCorners: UITabBar {
#IBInspectable var color: UIColor?
#IBInspectable var radii: CGFLoat = 15.0
private var shapeLayer: CALayer?
override func draw(_ rect: CGRect) {
addShape()
}
private func addShape() {
let shapeLayer = CAShapeLayer()
shapeLayer.path = createPath()
shapeLayer.strokeColor = UIColor.gray.withAlphaComponent(0.1).cgColor
shapeLayer.fillColor = color?.cgColor ?? UIColor.white.cgColor
shapeLayer.lineWidth = 1
if let oldShapeLayer = self.shapeLayer {
layer.replaceSublayer(oldShapeLayer, with: shapeLayer)
} else {
layer.insertSublayer(shapeLayer, at: 0)
}
self.shapeLayer = shapeLayer
}
private func createPath() -> CGPath {
let path = UIBezierPath(
roundedRect: bounds,
byRoundingCorners: [.topLeft, .topRight],
cornerRadii: CGSize(width: radii, height: 0.0))
return path.cgPath
}
}
Swift 5.3.1, XCode 11+, iOS 14
For using in storyboards:
import UIKit
class CustomTabBar: UITabBar {
override func awakeFromNib() {
super.awakeFromNib()
layer.masksToBounds = true
layer.cornerRadius = 20
layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner]
}
}
Subclassing UITabBarController then overried viewWillLayoutSubviews()
and add this code .
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.tabBar.layer.masksToBounds = true
self.tabBar.layer.cornerRadius = 12 // whatever you want
self.tabBar.layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner] // only the top right and left corners
}
This will be the result

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().