Sorry for stupid question, I'm newbie. Whole day I read a lot of answers and articles about using of self. But I still can't understand, why app crashes, if I change target from self to faceView in UITapRecognizer. What self refers to here? Is there any place in XCode to find it out? If you can advise any articles to read about this type of usage of self, it would be great too. Just in case, here is GitHub link to this project, if it's needed. Great thanks for help.
class FaceViewController: UIViewController {
#IBOutlet weak var faceView: FaceView!{
didSet {
let handlerPinch = #selector(FaceView.changeScale(byReactingOn:))
let pichRecognizer = UIPinchGestureRecognizer(target: faceView, action: handlerPinch)
faceView.addGestureRecognizer(pichRecognizer)
let handlerTap = #selector(openEyes(byReactingOn:))
let tapRecognizer = UITapGestureRecognizer(target: self, action: handlerTap)
faceView.addGestureRecognizer(tapRecognizer)
Related
My senior was reviewing my code and he found that I have used UIButton addTarget method like this
override func viewDidLoad() {
super.viewDidLoad()
self.btnAccount.addTarget(self, action: #selector(Accounts(_:)), for: .touchUpInside)
}
Now he is saying that you should not use addTarget in viewDidLoad it will take time(kind of memory management thing I didn't get it) to load view controller but I didn't find it relevant
that's why I am asking this question did I made some mistake by doing this should I always make actions
I didn't hear of that and even if it is true, you should never try to do premature optimization on your app. UIButton is a UIControl object, which follows an event-listener pattern, which is often implemented with a hashmap (NSDictionary in Objective-C) of targets ('aka' Listeners or Observers) and it is not very time-consuming operation.
I personally prefer to setup all UI component right at the beginning:
lazy var btnAccount: UIButton = {
let btn = UIButton
// setup button's appearance
btn.addTarget(self, action: #selector(Accounts(_:)), for: .touchUpInside)
return btn
}()
P.S. Please ask him about the source of the fact and let me know.
I have an image and I want it to go to my website when anyone hit the picture
I used tapGesture to convert the image to a big button , but what I don't know how to do it , is that I want the app to take the user to my website when the user hit the image
That depends a bit on where you want the link to open. The two standard approaches are to either open the URL in a UIWebView you provide inside the app, or to tell the system to open the link in the mobile Safari browser (which will send your app to the background).
To me it sounds like it this second behaviour you want. You can achieve it by telling the UIApplication to open the URL, like so:
#IBAction func linkTapped(sender:UITapGestureRecognizer) {
if let url = NSURL(string: "http://stackoverflow.com/") {
UIApplication.sharedApplication().openURL(url)
}
}
Edit:
Some more info on how to set this up in the way you described: in your viewDidLoad, set up your gesture recognizer like this:
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "linkTapped:")
self.yourImageView.addGestureRecognizer(tapGestureRecognizer)
self.yourImageView.userInteractionEnabled = true
Make sure the IBOutlet for yourImageView is connected correctly. Then simply add the code given in the original answer as a method to the same class containing your viewDidLoad method. If the gesture recognizer fires, it should now execute the code in the linkTapped: method and open the URL.
Edit 2:
And because it actually fits in ~10 lines of code, here's a minimal view controller class as an example implementation.
class ViewController: UIViewController {
#IBOutlet var myImageView: UIImageView! //Check if connected correctly!
override func viewDidLoad() {
super.viewDidLoad()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "linkTapped:")
myImageView.addGestureRecognizer(tapGestureRecognizer)
myImageView.userInteractionEnabled = true
}
func linkTapped(sender:UITapGestureRecognizer) {
if let url = NSURL(string: "http://stackoverflow.com/") {
UIApplication.sharedApplication().openURL(url)
}
}
}
Before you respond, keep in mind I am very new to swift (last time I coded was 2 years ago and that was OBJC), and I seem to be having an error. Here's a sample of my code:
init(sourceView:UIView, menuItems:Array<String>) {
originView = sourceView
sideBarTableViewController.tableData = menuItems
animator = UIDynamicAnimator(referenceView: originView)
let showGestureRecognizer:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
showGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right
originView.addGestureRecognizer(showGestureRecognizer)
let hideGestureRecognizer:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
}
I seem to be having errors with the UISwipeGestureRecognizer target. I can't set it to self, because it gives me this error: 'self' used before super.init call.
Any help is very much appreciated.
I don't think it's linked to the gesture recognisers. Try to modify your Init() method, by adding at the beginning (inside):
super.init()
This will initialize the object with the parameters of the class you are overriding. Also it will probably ask you to add override before your init method.
Exactly what the title implies. How do the gesture recognizers work, specifically UIGestureRecognizer. Here is a small snippet of my code
var keyboardDismiser: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "gestureRecognizer:")
keyboardDismiser.direction = .Right | .Left
noteView.addGestureRecognizer(keyboardDismiser)
and
func gestureRecognizer(sender: UISwipeGestureRecognizer!) {
println("swipe")
self.view.endEditing()
}
My goal is to dismiss the keyboard when switching from view to view in a UIScrollView with 3 pages. What am I doing wrong? There isn't much documentation on this in Swift.
First you setting the recognizer on the note view. It will only be active on the note view.
In addition, you are not setting direction correctly. You are setting then changing the it's value. To set it to both right and left, you use the | operator. Also direction knows it a UISwipeGestureRecognizerDirection so you don't need specify that.
var keyboardDismiser = UISwipeGestureRecognizer(target: self, action: "gestureRecognizer:")
keyboardDismiser.direction = .Right | .Left
self.view.addGestureRecognizer(keyboardDismiser)
Finally, I would use endEditing() instead of resignFirstResponder().
func gestureRecognizer(sender: UISwipeGestureRecognizer!) {
println("swipe")
self.view.endEditing(true)
}
Hope that helps.
I believe that selectors in Swift do not need the : at the end; they're just a string with the name of the function: gestureRecognizer. So this is what you should have:
var keyboardDismiser = UISwipeGestureRecognizer(target: self, action: "gestureRecognizer")
Relevant question here.
I'm writing some unit tests and, because of the nature of this particular app, it's important that I get as high up the UI chain as possible. So, what I'd like to do is programmatically trigger a button-press, as if the user had pressed the button in the GUI.
(Yes, yes -- I could just call the IBAction selector but, again, the nature of this particular app makes it important that I fake the actual button press, such that the IBAction be called from the button, itself.)
What's the preferred method of doing this?
It turns out that
[buttonObj sendActionsForControlEvents:UIControlEventTouchUpInside];
got me exactly what I needed, in this case.
EDIT: Don't forget to do this in the main thread, to get results similar to a user-press.
For Swift 3:
buttonObj.sendActions(for: .touchUpInside)
An update to this answer for Swift
buttonObj.sendActionsForControlEvents(.TouchUpInside)
EDIT: Updated for Swift 3
buttonObj.sendActions(for: .touchUpInside)
Swift 3:
self.btn.sendActions(for: .touchUpInside)
If you want to do this kind of testing, you’ll love the UI Automation support in iOS 4. You can write JavaScript to simulate button presses, etc. fairly easily, though the documentation (especially the getting-started part) is a bit sparse.
In this case, UIButton is derived from UIControl. This works for object derived from UIControl.
I wanted to reuse "UIBarButtonItem" action on specific use case. Here, UIBarButtonItem doesn't offer method sendActionsForControlEvents:
But luckily, UIBarButtonItem has properties for target & action.
if(notHappy){
SEL exit = self.navigationItem.rightBarButtonItem.action;
id world = self.navigationItem.rightBarButtonItem.target;
[world performSelector:exit];
}
Here, rightBarButtonItem is of type UIBarButtonItem.
For Xamarin iOS
btnObj.SendActionForControlEvents(UIControlEvent.TouchUpInside);
Reference
Swift 5:
class ViewController: UIViewController {
#IBOutlet weak var theTextfield: UITextField!
#IBOutlet weak var someButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
theTextfield.text = "Pwd"
someButton.sendActions(for: .touchUpInside)
}
#IBAction func someButtonTap(_ sender: UIButton) {
print("button tapped")
}
}
It's handy for people who write Unit Tests without UI Tests ;-)
Swift 5 way to solve it for UIBarButtonItem, which does not have sendAction method like UIButton etc.
extension UIBarButtonItem {
func sendAction() {
guard let myTarget = target else { return }
guard let myAction = action else { return }
let control: UIControl = UIControl()
control.sendAction(myAction, to: myTarget, for: nil)
}
}
And now you can simply:
let action = UIBarButtonItem(title: "title", style: .done, target: self, action: #selector(doSomething))
action.sendAction()
Swift 4:
self .yourButton(self)