Swift class with uibutton.addTarget to UIView not working - ios

I created a new file with the following class:
import Foundation
import UIKit
var Feld = classFeld()
class classFeld {
let button = UIButton()
func createButton() -> UIButton {
button.frame = CGRect(x: 10, y: 50, width: 200, height: 100)
button.backgroundColor=UIColor.black
button.addTarget(self, action: #selector(ButtonPressed(sender:)), for: .touchUpInside)
return button
}
#objc func ButtonPressed(sender: UIButton!) {
button.backgroundColor=UIColor.red
}
}
And this is my ViewController:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
mainview.addSubview(Feld.createButton())
self.view.addSubview(mainview)
}
var mainview=UIView()
}
When I start the app a black button is created but when I click on it it doesnt color red.
If I add the button instead of
mainview.addSubview(Feld.createButton())
to
self.view.addSubview(Feld.createButton())
it works and the button turns red.
May I anyone explain me why? It should make no difference if I add something to self.view or to a subview which is then added to self.view?

Because you need to give it a frame and add it to self.view
var mainview = UIView()

This is because you are just initializing a UIView without giving it any frame and adding it to the main view.
You need to give frame to your mainview also. For example :
class ViewController: UIViewController {
var mainview = UIView()
override func viewDidLoad() {
super.viewDidLoad()
mainview.frame = CGRect(x: 10, y: 50, width: 300, height: 300)
self.view.addSubview(mainview)
mainview.addSubview(Feld.createButton())
}
}

Here is changes on ViewController class and working fine:
class ViewController: UIViewController {
var mainview: UIView!
override func viewDidLoad() {
super.viewDidLoad()
mainview = UIView(frame: self.view.bounds)
mainview.addSubview(Feld.createButton())
self.view.addSubview(mainview)
}
}

Related

Cannot call method of a button from a custom UIView

I want to call an action from a button which is inside a custom View. The view itself is part of a UIViewController. But when I tapped the view, nothing happens. I do not know where my mistake is, although my code looks like the ones on stackoverflow.
protocol StoreDelegate: class {
func didPressButton(_ sender: UIButton)
}
class Store: UIView {
weak var delegate:StoreDelegate?
var button: UIButton = {
let button = UIButton()
button.setTitle("button", for: .normal)
button.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
button.backgroundColor = .red
button.addTarget(self, action: #selector(buttonPress(_:)), for: .touchUpInside)
return button
}()
override init(frame: CGRect) {
super.init(frame:frame)
self.addSubview(button)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#objc func buttonPress(_ sender: UIButton) {
delegate?.didPressButton(sender)
print("here")
}
}
And this is my ViewController:
class ViewController: UIViewController, StoreDelegate{
var testView = Store()
override func viewDidLoad() {
super.viewDidLoad()
testView.delegate = self
self.view.addSubview(testView)
}
func didPressButton(_ sender: UIButton) {
print("Hello")
}
}
Neither it prints "Hello" nor "Here". Maybe I have misunderstood the protocol/delegate pattern.
You need to set constraints or a frame to the view
testView.frame = ///////
It's the base behind receiving actions
You can implement override sizeToFit in Store class to match your needs:
override func sizeToFit() {
frame.size = button.frame.size
}
Then you can call it like:
testView.sizeToFit()
You may consider using autolayout for better sizing.

How to access views created in viewDivLoad

class ViewController: UIViewController
{
#IBAction func button_down(_ sender: Any)
{
do_something(view: myView);
}
override func viewDidLoad()
{
super.viewDidLoad();
let screen_size: CGRect = UIScreen.main.bounds;
var myView = UIView(frame: CGRect(x: 0, y: screen_size.height/2 - screen_size.width/2, width: screen_size.width, height: screen_size.width));
myView.backgroundColor = UIColor.red;
self.view.addSubview(myView);
}
}
When I try to compile this code, I get an error:
Use of unresolved identifier 'myView'
How can I solve this problem? I have tried declaring myView outside of viewDivLoad, but that's not permitted.
You should definitely do some research on the concept of "scope" in computer programming - it'll be difficult to go too far without it. myView only exists within the scope of viewDidLoad. If you want it to be available outside of that, you can make it a property of the class like so:
class ViewController: UIViewController
{
var myView: UIView!
#IBAction func buttonDown(_ sender: Any)
{
doSomething(view: myView)
}
override func viewDidLoad()
{
super.viewDidLoad()
let screenSize: CGRect = UIScreen.main.bounds
myView = UIView(frame: CGRect(x: 0, y: screenSize.height/2 - screenSize.width/2, width: screenSize.width, height: screenSize.width))
myView.backgroundColor = UIColor.red
self.view.addSubview(myView)
}
}
A couple of other notes:
You don't need semicolons at the end of lines in Swift.
It seems you're using Interface Builder, so I would suggest creating myView that way instead of programmatically.
Function and variable names in Swift should be camel cased - so buttonDown instead of button_down, screenSize instead of screen_size.

IOS Swift3 how to Remove Custom UIView randomly

I am building an iOS Application in swift 3, where I am creating dynamic UIViews. I need to remove custom view randomly. Please help me I am stuck with this for a long time. Thanks In Advance
class ViewController: UIViewController {
var myView: subView!
var y : CGFloat!
#IBOutlet weak var addButton: UIButton!
override func viewDidLoad() {
y = 1
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func cancelbutton(_ sender: UIButton) {
myView.removeFromSuperview()
}
#IBAction func buttonAction(_ sender: Any) {
y = y + 110
myView = subView(frame: CGRect(x: 80, y: y, width: 300, height: 100))
myView.backgroundColor = UIColor.green
myView.actionButton.addTarget(self, action: (#selector(cancelbutton(_:))), for: UIControlEvents.touchUpInside)
self.view.addSubview(myView)
}
}
As you can see in the above image when i click on Close the SubView(custome View) closes, but where as MyView with green color does not go and stays there. Someone please Help.........
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
Bundle.main.loadNibNamed("subView",owner: self, options:nil)
self.addSubview(self.views)
Bundle.main.loadNibNamed("subView",owner: self, options:nil)
self.addSubview(self.views)
}
override init(frame: CGRect)
{
super.init(frame: frame)
Bundle.main.loadNibNamed("subView", owner: self, options: nil)
views.frame = bounds
self.addSubview(self.views)
}
#IBAction func buttonAction(_ sender: Any) {
views.removeFromSuperview()
}
The thing you are doing wrong is that you add multiple views of subView that why you selected does not remove. Please modify your code like given below.
The thing I have done is that whenever you will add new subView you will also set its tag value and when you select view to remove its tag value and place an if statement on that tag value.
class ViewController: UIViewController {
var myView: subView!
var y : CGFloat!
var tag : Int = 0
#IBOutlet weak var addButton: UIButton!
override func viewDidLoad() {
y = 1
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func cancelbutton(_ sender: UIButton)
{
let selectViewTagValue : Int = sender.tag /// save the selected view tag value
for object in self.view.subviews {
if ((object is subView) && object.tag == selectViewTagValue)
{
object.removeFromSuperview()
}
}
}
#IBAction func buttonAction(_ sender: Any) {
y = y + 110
myView = subView(frame: CGRect(x: 80, y: y, width: 300, height: 100))
myView.tag = tag
myView.actionButton.tag = tag
tag = tag + 1
myView.backgroundColor = UIColor.green
myView.actionButton.addTarget(self, action: (#selector(cancelbutton(_:))), for: UIControlEvents.touchUpInside)
self.view.addSubview(myView)
}
Try to change cancel action like this:
func cancelbutton(_ sender: UIButton)
{
if let myView = sender.superview {
myView.removeFromSuperview()
}
}
Just remove the button's container view, not the global myView.
I managed to fixed the delete issue, but currently I am unable to relocate the positions the customs views, as shows in the picture below, Kindly help me with this.

UIScrollViewDelegate Not Being Called in Custom Class

When I instantiate and add a scroll view to my self.view in my ViewController class and set the scroll view's delegate to self, the delegate functions get called. As written below:
class ViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var smallView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let width = Double(view.frame.width)
let height = Double(view.frame.height)
let frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)
let scrollView = UIScrollView(frame: frame)
//scrollView.backgroundColor = UIColor.blue
let size = CGSize(width: width + 300, height:1000)
scrollView.contentSize = size
smallView.addSubview(scrollView)
scrollView.delegate = self
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("Gets called.")
}
}
However, when I create a custom class, in this case called, PhotoBooth, and call try to call the delegate function in this custom class, the functions do not get called. Here is my custom class:
import Foundation
import UIKit
class PhotoBooth: NSObject, UIScrollViewDelegate {
private var boothView: UIView
//private var scrollView: UIScrollView
init(view: UIView) {
boothView = view
}
func startSession() {
let width = Double(boothView.frame.width)
let height = Double(boothView.frame.height)
let frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)
let scrollView = UIScrollView(frame: frame)
//scrollView.backgroundColor = UIColor.blue
let size = CGSize(width: width + 300, height:1000)
scrollView.contentSize = size
boothView.addSubview(scrollView)
scrollView.delegate = self
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("paisdjfij")
}
}
And I instantiate the class in my ViewController like so:
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
#IBOutlet weak var smallView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let photoBooth = PhotoBooth(view: self.view)
photoBooth.startSession()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Any solutions to the problem? Please let me know and thank you so much for your help in advance.
Instead of trying this You should use protocols to call scroll view in custom class.It will look somewhat like this.
CustomClass.h
#protocol CustomDelegate <NSObject>
-(void)customDelegateMethod;
#end
#interface CustomClass : UIScrollView <UIScrollViewDelegate>
{
id<CustomDelegate> delegate
}
CustomClass.m
-(void) methodScrollView
{
[self.delegate customDelegateMethod];
}
ViewController.h
#interface ViewController: UIViewController <CustomDelegate>
{
}
ViewController.m
-(void)makeCustomScrollView
{
CustomClass *objCustom = [[CustomClass alloc] init];
objCustom.delegate = self;
//other stuff
}
-(void)customDelegateMethod
{
}

Subview of UIScrollView don't resize (manually)

I have a UIScrollView with a UIView inside of it. When I try to manually resize the UIView by code, it doesn't work. I tried to set the autoResizingMask property of the UIView to .None and I implemented the touchesShouldCancelInContentView method of the UIScrollView to return true but it still doesn't work. Here's my code :
class ViewController: UIViewController {
#IBOutlet var scrollView: CustomScrollView!
#IBOutlet var field: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
var gesture = UITapGestureRecognizer(target: self, action: "gestureHandler")
gesture.numberOfTapsRequired = 1
view.addGestureRecognizer(gesture)
scrollView.contentSize = CGSizeMake(430, 140)
field.autoresizingMask = .None
}
func gestureHandler() {
field.frame.size.width += 20
var view = UIView(frame: CGRectMake(0, 0, 30, 100))
view.backgroundColor = UIColor.redColor()
field.frame.size.width -= 30
field.frame.origin.x += 30
scrollView.addSubview(view)
}
}
class CustomScrollView: UIScrollView {
override func touchesShouldCancelInContentView(view: UIView!) -> Bool {
return true
}
}
What I get :
What I want :
Thanks for your help !

Resources