How to remove a programmatically created subview from Superview when button touch up inside? - ios

I have a system that generate new view (marked with blue rect on the picture) and button (marked with green circle ) as a subview of Superview(marked with red rect) when user tapped to another button(named as Button). They all created programmatically. I can remove the "minus button" according it's button.tag with Action Messages. The problem is that how do I remove that subview next to minus button? It has also same tag with minus button.
My mainButton IBAction below ;
#IBAction func mainButton(sender: UIButton) {
drawThem()
minusButtonY = counter == 0 ? (minusButtonY + 101) :(minusButtonY + 68)
borderY = counter == 0 ? (borderY + 86) : (borderY + 68)
counter++
drawFooter()
completePaymentView.contentSize = counter > 7 ? (CGSizeMake(500.0, ( borderY ))) : (CGSizeMake(500.0, ( 490.0 )))
}
And the the method where I generate new view and button ;
func drawThem() {
//creating minus button
let image = UIImage(named: "minus.png") as UIImage?
let button = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
var mX : CGFloat = 2.0
var mY : CGFloat = minusButtonY >= 36.0 ? minusButtonY : 36.0
button.frame = CGRectMake(mX, mY, 22, 22)
button.setImage(image, forState: .Normal)
button.tag = Int(counter)
button.addTarget(self, action:"btnTouched:", forControlEvents:.TouchUpInside)
completePaymentView.addSubview(button)
//drawing payment section border
var x : CGFloat = 43.0
var y : CGFloat = borderY >= 20.0 ? borderY : 20.0
let size = CGSize(width: 485 , height: 55)
let borderView = UIView(frame: CGRect(origin: CGPoint(x: x , y: y), size: size))
borderView.layer.borderColor = UIColor(red: 0.83, green: 0.85, blue: 0.88, alpha: 1.0).CGColor
borderView.layer.borderWidth = 2.0
borderView.layer.cornerRadius = 5.0
borderView.tag = counter
completePaymentView.addSubview(borderView)
//drawing UIImage and Labels into border
let imageName = "circle.png"
let thumb = UIImage(named: imageName)
let imageView = UIImageView(image: thumb!)
imageView.frame = CGRect(x: 14, y: 8, width: 55, height: 35)
borderView.addSubview(imageView)
let label1 = UILabel(frame: CGRect(x: 85, y: 20, width: 100, height: 18)) as UILabel
label1.text = "Some Text"
label1.textColor = UIColor(red: 0.49, green: 0.54, blue: 0.6, alpha: 1.0)
label1.font = label1.font.fontWithSize(14.0)
label1.textAlignment = .Left
borderView .addSubview(label1)
let label2 = UILabel(frame: CGRect(x: 370, y: 20, width: 100, height: 18)) as UILabel
label2.text = "Some Text"
label2.textColor = UIColor(red: 0.49, green: 0.54, blue: 0.6, alpha: 1.0)
label2.font = label2.font.fontWithSize(14.0)
label2.textAlignment = .Right
borderView .addSubview(label2)
}
and Target Action below ;
func btnTouched(button : UIButton){
button.removeFromSuperview()
}

Add the following in btnTouched method. Actually I am searching through all the subviews to find the tag.
for view in self.view.subviews as! [UIView] {
if view.tag == button.tag {
view.removeFromSuperview()
}
}

Related

How to Change uitextfield leftView image tintColor on editing

I'm trying to achieve UITextField editing or not editing style like this:
But the trickiest part for me is How to change that left image tint color. I have achieved this so far:
My code:
UITextField
lazy var email: UITextField = {
let name = UITextField()
name.layer.cornerRadius = 17.5
name.layer.borderColor = UIColor(red: 0.55, green: 0.61, blue: 0.69, alpha: 0.5).cgColor
name.layer.borderWidth = 1.5
name.placeholder = "Email"
name.font = UIFont.systemFont(ofSize: 15)
name.textColor = UIColor(red: 0.55, green: 0.61, blue: 0.69, alpha: 1)
name.backgroundColor = .clear
name.leftViewMode = UITextFieldViewMode.always
name.delegate = self
name.translatesAutoresizingMaskIntoConstraints = false
return name
}()
leftImage func:
func addLeftImageTo(txtField: UITextField, andImage img: UIImage) {
let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 42.75, height: 40))
let centerX: CGFloat = (leftView.frame.midX) - (img.size.width / 2)
let centerY: CGFloat = (leftView.frame.midY) - (img.size.height / 2)
let leftImageView = UIImageView(frame: CGRect(x: centerX + 2 , y: centerY - 1, width: img.size.width, height: img.size.height))
leftImageView.contentMode = .scaleAspectFit
leftImageView.image = img
leftView.addSubview(leftImageView)
txtField.leftView = leftView
txtField.leftViewMode = .always
}
Adding leftImages:
let emailLeftImg = UIImage(named: "ic_txt_field_email")
addLeftImageTo(txtField: email, andImage: emailLeftImg!)
let passwordLeftImg = UIImage(named: "ic_txt_field_password")
addLeftImageTo(txtField: password, andImage: passwordLeftImg!)
editingBegains and Ending:
func textFieldDidBeginEditing(_ textField: UITextField) {
self.setTextBorder(textField: textField, color: UIColor.white, borderColor: UIColor.white, isSelected: true)
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.setTextBorder(textField: textField, color: UIColor.clear, borderColor: UIColor(red: 0.55, green: 0.61, blue: 0.69, alpha: 0.5), isSelected: false)
}
func setTextBorder(textField: UITextField, color: UIColor, borderColor: UIColor, isSelected: Bool) {
textField.backgroundColor = color
textField.layer.borderColor = borderColor.cgColor
textField.tintColor = UIColor(red: 1.0, green: 0.2, blue: 0.33, alpha: 1)
textField.layer.masksToBounds = false
if isSelected == true {
textField.layer.shadowRadius = 3.0
textField.layer.shadowColor = UIColor.black.cgColor
textField.layer.shadowOffset = CGSize(width: 0, height: 2)
textField.layer.shadowOpacity = 0.125
} else {
textField.layer.shadowRadius = 0
textField.layer.shadowColor = UIColor.clear.cgColor
textField.layer.shadowOffset = CGSize(width: 0, height: 0)
textField.layer.shadowOpacity = 0
}
}
I had tried adding this code to change Image color but it didn't work.
var picTintColor: Bool = false
In LeftImage func:
if picTintColor == true {
leftImageView.image = img.withRenderingMode(.alwaysTemplate)
leftImageView.tintColor = .blue
} else {
leftImageView.image = img
}
And in editingBegains and Ending func:
if isSelected == true {
picTintColor = true
} else {
picTintColor = false
}
I'm a complete noob in IOS programming so thanks for your patience and sorry for my bad english. Thanks!
According the code ,it actually can not pass isSelected signal to the leftImageView,maybe leftImageView get in laster is not the earlier ,or the signal not pass successly.
I suggest that a easy way to do, just in editingBegains and Ending: to do what you want change the imageview,like this:
func textFieldDidBeginEditing(_ textField: UITextField) {
let emailLeftImg = UIImage(named: "ic_txt_field_email")
addLeftImageTo(txtField: email, andImage: emailLeftImg!)
}
func addLeftImageTo(txtField: UITextField, andImage img: UIImage) {
let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 42.75, height: 40))
let centerX: CGFloat = (leftView.frame.midX) - (img.size.width / 2)
let centerY: CGFloat = (leftView.frame.midY) - (img.size.height / 2)
let leftImageView = UIImageView(frame: CGRect(x: centerX + 2 , y: centerY - 1, width: img.size.width, height: img.size.height))
leftImageView.contentMode = .scaleAspectFit
if picTintColor == true {
leftImageView.image = img.withRenderingMode(.alwaysTemplate)
leftImageView.tintColor = .blue
} else {
leftImageView.image = img
}
leftView.addSubview(leftImageView)
txtField.leftView = leftView
txtField.leftViewMode = .always
}
and in end delgate method ,just do that ,you can try this way to test.Hope to help you.

add drop shadow on a table view header

I have this following header for my table view header section
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
view.backgroundColor = .white
// add a button
let button = UIButton(type : .system)
button.showsTouchWhenHighlighted = false
button.frame = CGRect(x: 0 , y: 0 , width: 20 , height: 20 )
if(collapsed[section])
{ button.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)}
else
{ button.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)}
button.addTarget(self, action: #selector(reloadTable), for: .touchUpInside)
button.tag = section
view.addSubview(button)
button.bindFrameToSuperviewBounds()
// add an Image
let image = UIImageView(image: UIImage(named: "sup1"))
image.frame = CGRect(x: 150 , y: 5 , width: 100 , height: 100)
image.contentMode = .scaleAspectFit
view.addSubview(image)
// add a label
let lblNew = UILabel()
lblNew.frame = CGRect(x: 20, y: 100 , width: 100, height: 30)
lblNew.text = "١٢٣ ر.س"
lblNew.textColor = UIColor.myDarkGreen
lblNew.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(lblNew)
// view.dropShadow()
return view
}
Now I want to add drop shadow effect on the section header to look like this
I have tried some solutions here but it works on simple view that is not used as a viewForHeaderInSection, any tips?
Use the view's layer's shadow properties:
view.layer.shadowOpacity = 1
view.layer.shadowOffset = CGSize(width: 0, height: 1)
view.layer.shadowRadius = 1
Result:

Center a UILabel of a UIView

I am currently trying to make a simple pop up, here I have a button, once it gets tapped.
It should show a simple view above it, I achieved the blue background, but I am not being able to add a label to it, and center the label to the blue popup
let width = (sender as! UIButton).frame.width
let y = (sender as! UIButton).frame.origin.y
let x = (sender as! UIButton).frame.origin.x
myView = UIView(frame: CGRect(x: x, y: y - 30, width:width, height: 30))
myView.backgroundColor = UIColor.blue
let label = UILabel()
label.text = (sender as! UIButton).titleLabel?.text
label.font = UIFont(name:"avenirNext-Meduim",size:20)
label.center = self.myView.center
myview.addSubview(label)
self.view.addSubview(myView)
UIView.animate(withDuration: 0.1, delay: 0.1, options: [], animations: {
self.myView.alpha = 0.0
}) { (finished: Bool) in
self.myView.isHidden = true
}
Try to set your label frame:
let label = UILabel(frame: CGRect(origin: .zero, size: yourLabelSize))
Instead of
label.center = self.myView.center
try
label.centerXAnchor.constraint(equalTo: myView.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: myView.centerYAnchor).isActive = true
after
myview.addSubview(label)
self.view.addSubview(myView)
My solution
let codedLabel:UILabel = UILabel()
codedLabel.frame = CGRect(x: myView.center.x, y: myView.center.y, width: 51, height: 30)
codedLabel.textAlignment = .center
codedLabel.text = "q"
codedLabel.numberOfLines = 1
codedLabel.textColor=UIColor.red
codedLabel.font=UIFont.systemFont(ofSize: 22)
codedLabel.backgroundColor=UIColor.lightGray
self.myView.addSubview(codedLabel)
codedLabel.translatesAutoresizingMaskIntoConstraints = false
codedLabel.heightAnchor.constraint(equalToConstant: 30).isActive = true
codedLabel.widthAnchor.constraint(equalToConstant: 30).isActive = true
codedLabel.centerXAnchor.constraint(equalTo: codedLabel.superview!.centerXAnchor).isActive = true
codedLabel.centerYAnchor.constraint(equalTo: codedLabel.superview!.centerYAnchor).isActive = true
let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 50))
let label = UILabel()
label.frame = CGRect.init(x: headerView.center.x-60, y:headerView.center.y-15, width: 120, height: 30)
label.textAlignment = .center
label.textColor = #colorLiteral(red: 0.1290470958, green: 0.2743584514, blue: 0.6418049335, alpha: 1)
label.font = UIFont(name: "Roboto-Bold", size: 15)
label.text = "11-12-2020"
headerView.addSubview(label)
headerView.backgroundColor = #colorLiteral(red: 0.9967060685, green: 0.9998621345, blue: 0.9997505546, alpha: 1)

TicTacToe how to reset containerView content?

I need some help over here. I try to learn... some things and practice but i'm not able to manage that function.
I have this function creating the container view:
func createGameView() {
let containerView = UIView()
containerView.frame = CGRect(x: 0,
y: self.screenHeight * 0.4,
width: screenWidth,
height: screenHeight * 0.6)
containerView.backgroundColor = UIColor(red:0.99, green:0.13, blue:0.00, alpha:1)
self.view.addSubview(containerView)
After that I have a function who will populate the container view with 9 squares
func createGridView( _ container : UIView) {
let buttonWidth = container.frame.size.width / 3
let buttonHeight = container.frame.size.height / 3
for i in [0,1,2] {
for j in 0...2 {
let button = UIButton(frame:
CGRect( x : buttonWidth * CGFloat (i),
y :buttonHeight * CGFloat (j),
width : buttonWidth,
height : buttonHeight ))
button.backgroundColor = UIColor.init(colorLiteralRed: 0.1, green: 0.89, blue: 0.05, alpha: 1)
button.layer.borderColor = UIColor.black.cgColor
button.layer.borderWidth = 1.0
container.addSubview(button)
button.addTarget(self, action: #selector(GameViewController.addGameValue(sender:)), for: .touchUpInside)
button.tag = i + 3 * j
self.gameButtons.append(button)
}
}
}
And I have a button called RESET
var resetButton = UIButton(frame:
CGRect(x: Double(containerView.frame.size.width - 100),
y: Double(containerView.frame.size.height - 60),
width: 60,
height: 40.0)
)
resetButton.setTitle ("Reset", for: UIControlState.normal)
resetButton.setTitleColor(UIColor.black, for: UIControlState.normal)
resetButton.setTitleColor(UIColor.white, for: .highlighted)
resetButton.layer.borderWidth = 1.0
resetButton.layer.borderColor = UIColor.black.cgColor
resetButton.layer.cornerRadius = 5.0
resetButton.addTarget(self, action: #selector(GameViewController.resetGame), for: UIControlEvents.touchUpInside)
containerView.addSubview(resetButton)
This is where i got a problem :(
func resetGame (sender: UIButton) {
// .addTarget(self, action: #selector(self.createGameView), for: .touchUpInside)
print(" reset me ")
// .addTarget(self, action: #selector(GameViewController.resetGame), for: .touchUpInside)
}
Anyone can tell me why none of those are not working to reset the value ? Is a tic tac toe game, and after put some x and 0 i want to restore the gridView to intial state. Got no ideea how to do it.
you already have all of the buttons that you need added to the view after createGridView is called, so on reset all you have to do is reset the button state, clear any scores/points and your ready to start again.
func resetGame() {
// reset any scores, colors etc
for button in self.gameButtons {
button.setTitle ("", for: UIControlState.normal)
button.backgroundColor = UIColor.init(colorLiteralRed: 0.1, green: 0.89, blue: 0.05, alpha: 1)
}
}

Swift - Apply Shadow to circular button on click

I am creating circular buttons as follow:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = GradientButton.createCircularButton(20, yPos: 20, width: 30, height: 30, circleValue:20)
button.addTarget(self, action: #selector(ViewController.didCircleBtnTouched(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
}
}
enum ColorType {
case red, green, orange
}
class GradientButton: UIButton {
var colorType: ColorType?
public class func createCircularButton(xPos: CGFloat, yPos: CGFloat, width: CGFloat, height: CGFloat, circleValue: Int) -> GradientButton {
let button = GradientButton()
button.titleLabel!.font = UIFont(name:"HelveticaNeue", size: 12)
let buttonFrame = CGRect(x: xPos, y: yPos, width: width, height: height)
button.frame = buttonFrame
button.backgroundColor = UIColor.clearColor()
button.backgroundColor = UIColor.whiteColor()
button.layer.borderWidth = 1
button.layer.cornerRadius = 15.0
//this helps making it circular not rectangle
button.clipsToBounds = true
let red = UIColor(red:134/255, green:16/255, blue:1/255, alpha:1.0)//red
let green = UIColor(red:0/255, green:136/255, blue:43/255, alpha:1.0)//green
let orange = UIColor(red:243/255, green:144/255, blue:25/255, alpha:1.0)//orange
if(circleValue <= 3){
button.colorType = .green
button.layer.borderColor = UIColor.greenColor().CGColor
button.setTitleColor(green, forState: .Normal)
} else if(circleValue > 3 && circleValue <= 7){
button.colorType = .orange
button.layer.borderColor = UIColor.orangeColor().CGColor
button.setTitleColor(orange, forState: .Normal)
} else if(circleValue > 7){
button.colorType = .red
button.layer.borderColor = UIColor.redColor().CGColor
button.setTitleColor(red, forState: .Normal)
}
button.setTitle("\(circleValue)", forState: .Normal)
return button
}
}
And on click of button I am applying gradient as follow:
func didCircleBtnTouched(sender:GradientButton!){
ApplyGradientToButton(sender)
}
func ApplyGradientToButton(sender: GradientButton!){
var color1 = UIColor()
var color2 = UIColor()
if(sender.colorType == .red){
color1 = UIColor(red:134/255, green:16/255, blue:1/255, alpha:1.0)
color2 = UIColor(red:200/255, green:37/255, blue:6/255, alpha:1.0)
}
else if(sender.colorType == .green) {
color1 = UIColor(red:0/255, green:136/255, blue:43/255, alpha:1.0)
color2 = UIColor(red:112/255, green:191/255, blue:65/255, alpha:1.0)
}
else if(sender.colorType == .orange) {
color1 = UIColor(red:200/255, green:110/255, blue:1/255, alpha:1.0)
color2 = UIColor(red:239/255, green:149/255, blue:26/255, alpha:1.0)
}
sender.setTitleColor(UIColor.whiteColor(), forState: .Normal)
var layer = sender.layer
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
layer.shadowOpacity = 1.0
layer.shadowRadius = 10.0
sender.applyGradient([color2, color1], locations: [0.0, 0.90])
}
I need to display shadow around circular button on button click. But shadow is not getting displayed.
I think button.clipsToBounds = true is responsible as when I am not using this property shadow appears. Unfortunately by removing this property my circular button becomes rectangular after click which is not desirable.
Is there any way to display the shadow without changing the shape of button?
Please advise?
Current output:
Expected output:
Well you can't clip/mask to bounds and add a shadow, as it will also be clipped or masked too.
The solution is to add the shadow on a separate layer and add the image as a sublayer.
This is described in many posts here:
https://stackoverflow.com/a/25591916/312312
Swift - Problems with corner radius and drop shadow
and many many more
Just Put this code in viewController.swift file.. (Or any other file)
extension UIView {
func setRadiusWithShadow(_ radius: CGFloat? = nil) {
self.layer.cornerRadius = radius ?? self.frame.width / 2
self.layer.shadowColor = UIColor.darkGray.cgColor
self.layer.shadowOffset = CGSize(width: 1.5, height: 1.5)
self.layer.shadowRadius = 1.0
self.layer.shadowOpacity = 0.7
self.layer.masksToBounds = false
}
}
and then apply to your button..
btnEdit.setRadiusWithShadow()
Yeah... Just see the output... Everything is done...
Note: You can change CGSize(width: 1.5, height: 1.5) values as per your desired need...

Resources