Storyboard, does not recognize UIControl actions anymore - ios

This project runs and compiles fine, but in all storyboards if I was on a UIControl (such as a UIButton) interface builder doesn't seems able to detect it as the correct class.
As you can see in the connection inspector the action. The connection is spotted with an exclamation mark.
The identity inspector shows the class correctly.
I already tried to fully clean the project, even derived data.
Project build and runs fine but I can't connect actions anymore.
Any suggestion?

Apparently this seems a bug in Xcode.
To reproduce it you just need to make a protocol and make a UIButton conform to it.
This test few lines, breaks everything and you are no longer able to create and make connections from IB and the source file:
protocol TestProcol {
var test: String { get set }
}
extension UIButton: TestProcol {
var test: String {
set(val) {
titleLabel?.text = val
}
get {
return (titleLabel?.text!)!
}
}
}

Related

MessageKit set up MessageLabelDelegate for didSelectURL

I'm trying to open url from messages embedded in an NSAttributedString. I'm using the latest version of MessageKit. I'm using the function didSelectURL, but it doesn't seem to reach that part of the code. I came across this solution, but I wanted to follow up with regards to how to set up MessageLabelDelegate. Just like in the linked solution, I have implemented the delegate methods detectorAttributes and enabledDetectors.
I currently have MessageLabelDelegate set up as an extension to my ViewController, but it never seems to reach those methods.
extension ChatViewController:MessageLabelDelegate {
func didSelectURL(_url: URL) {
// .. open URL
}
}
It seems to be getting overwritten by the method didTapMessage in the MessageCellDelegate extension. I tried going through the example code in the MessageKit repo, but still unclear as to how it's meant to be set up or what I'm doing wrong.
UPDATE: The problem was the way I was declaring the NSAttributedString. I was setting its value as a string instead of a URL.
The MessageCellDelegate implements the the MessageLabelDelegate so you need to make sure that the messagesCollectionView.messageCellDelegate is set to the ChatViewController and that the ChatViewController has an extension for MessageCellDelegate where you can put your didSelectURL
public protocol MessageCellDelegate: MessageLabelDelegate {

Compile and runtime failures when importing interfaces with category extensions in XCode 7

I'm trying to get an example of running OpenEars with the RapidEars plugin running in Swift 2.2 (XCode 7.3.1). However, I suspect I'm having a larger issue with using Objective-C interfaces with extensions in a Swift project (or my understanding of how that works).
The OpenEars code is Obj-C. However I was able to get it running in my swift project through the standard Obj-C -> Swift translation techniques.
Abbreviated code follows. The full example is on a forked Github and updated to Swift-2.2: https://github.com/SuperTango/OpenEars-with-Swift-
This following example is working great. You can see the entire project by checkng out the "working-opears-swift2.2" tag.
OpenEarsTest-Bridging-Header.h:
#import <OpenEars/OELanguageModelGenerator.h>
#import <OpenEars/OEAcousticModel.h>
#import <OpenEars/OEPocketsphinxController.h>
#import <OpenEars/OEAcousticModel.h>
#import <OpenEars/OEEventsObserver.h>
ViewController.swift:
class ViewController: UIViewController, OEEventsObserverDelegate {
var openEarsEventsObserver = OEEventsObserver()
override func viewDidLoad() {
super.viewDidLoad()
loadOpenEars()
}
func loadOpenEars() {
self.openEarsEventsObserver = OEEventsObserver()
self.openEarsEventsObserver.delegate = self
var lmGenerator: OELanguageModelGenerator = OELanguageModelGenerator()
addWords()
var name = "LanguageModelFileStarSaver"
lmGenerator.generateLanguageModelFromArray(words, withFilesNamed: name, forAcousticModelAtPath: OEAcousticModel.pathToModel("AcousticModelEnglish"))
lmPath = lmGenerator.pathToSuccessfullyGeneratedLanguageModelWithRequestedName(name)
dicPath = lmGenerator.pathToSuccessfullyGeneratedDictionaryWithRequestedName(name)
}
func startListening() {
do {
try OEPocketsphinxController.sharedInstance().setActive(true)
OEPocketsphinxController.sharedInstance().startListeningWithLanguageModelAtPath(lmPath, dictionaryAtPath: dicPath, acousticModelAtPath: OEAcousticModel.pathToModel("AcousticModelEnglish"), languageModelIsJSGF: false)
} catch {
NSLog("Error!")
}
}
// A whole bunch more OEEventsObserverDelegate methods that are all working fine...
func pocketsphinxDidStartListening() {
print("Pocketsphinx is now listening.")
statusTextView.text = "Pocketsphinx is now listening."
}
Up until this point, everything is working great.
However, In order to use the "RapidEars" plugin, the documentation (http://www.politepix.com/rapidears/) says to:
Add the framework to the project and ensure it's being included properly.
import two new files (that are both "categories" to existing OpenEars classes):
#import <RapidEarsDemo/OEEventsObserver+RapidEars.h>
#import <RapidEarsDemo/OEPocketsphinxController+RapidEars.h>
Change methods that used: startListeningWithLanguageModelAtPath to use startRealtimeListeningWithLanguageModelAtPath
add two new OEEventsObservableDelegate methods.
func rapidEarsDidReceiveLiveSpeechHypothesis(hypothesis: String!, recognitionScore: String!)
func rapidEarsDidReceiveFinishedSpeechHypothesis(hypothesis: String!, recognitionScore: String!)
The new code can be found by checking out the rapidears-notworking-stackoverflow tag from the above github repo
Problem 1:
When doing completion in the XCode editor, the editor sees WILL perform autocompletion on the startRealtimeListeningWithLanguageModelAtPath method, however when the code is run, it always fails with the error:
[OEPocketsphinxController startRealtimeListeningWithLanguageModelAtPath:dictionaryAtPath:acousticModelAtPath:]: unrecognized selector sent to instance 0x7fa27a7310e0
Problem 2:
When doing auto completion in the XCode editor, it doesn't see the two new delegate methods defined in RapidEarsDemo/OEPocketsphinxController+RapidEars.h.
I have a feeling that these are related, and also related to the fact that they failing methods are defined as Categories to Objective-C classes. But that's only a guess at this point.
I've made sure that the RapidEars framework is imported and in the framework search path.
Can anyone tell me why this is happening? Or if there's some Swift magic incantation that I missed?
The problem could be the one described in the link below, where category methods in a static library produce selector not recognized runtime errors.
Technical Q&A QA1490: Building Objective-C static libraries with categories

Know at runtime that you are running in IBDesignable

(programming in swift 2)
In my iOS application I am using frameworks. I am also using the IBDesignable feature with great success. I have a bunch of views and buttons in frameworks that are IBDesignable and thus render nicely on the screen of interface builder.
Problem is that one of these views executes code when its initialized that will do an assertion if its being run just in the context of the IBDesignable interfacebuilder (executed just to render the IB screen). The reason for the assertion is valid, and really does not matter, bottom line is that I do not want to loose this functionality during "normal" operation.
My idea for a solution is to know when the code is being executed just for rendering in IB for IBDesignable mode, and thus build in a switch to not/do the assert.
I tried using the #if !TARGET_INTERFACE_BUILDER but this is not working, as this is a preprocessor directive and thus only evaluated a compile time, and the frameworks are precompiled (when used in the actual app).
I also thought about using prepareForInterfaceBuilder() but this is not applicable because the class throwing the assert has nothing todo with UIView itself.
Is there a function or any other way to check AT RUNTIME (in a framework) that your code is being run as part of IB screen rendering for IBDesignable mode?
After testing a few dozens solutions, I found the following to work reliably:
/**
Returns true if the code is being executed as part of the Interface Builder IBDesignable rendering,
so not for testing the app but just for rendering the controls in the IB window. You can use this
to do special processing in this case.
*/
public func runningInInterfaceBuilder() -> Bool {
//get the mainbundles id
guard let bundleId = NSBundle.mainBundle().bundleIdentifier else {
//if we don't have a bundle id we are assuming we are running under IBDesignable mode
return true
}
//when running under xCode/IBDesignable the bundle is something like
//com.apple.InterfaceBuilder.IBCocoaTouchPlugin.IBCocoaTouchTool
//so we check for the com.apple. to see if we are running in IBDesignable rendering mode
//if you are making an app for apple itself this would not work, but we can live with that :)
return bundleId.rangeOfString("com.apple.") != nil
}
SWIFT 4 version
/**
Returns true if the code is being executed as part of the Interface Builder IBDesignable rendering,
so not for testing the app but just for rendering the controls in the IB window. You can use this
to do special processing in this case.
*/
public func runningInInterfaceBuilder() -> Bool {
//get the mainbundles id
guard let bundleId = Bundle.main.bundleIdentifier else {
//if we don't have a bundle id we are assuming we are running under IBDesignable mode
return true
}
//when running under xCode/IBDesignable the bundle is something like
//com.apple.InterfaceBuilder.IBCocoaTouchPlugin.IBCocoaTouchTool
//so we check for the com.apple. to see if we are running in IBDesignable rendering mode
//if you are making an app for apple itself this would not work, but we can live with that :)
return bundleId.contains("com.apple.")
}

'Use of Unresolved Identifier' in Swift

So I have been making an app, and everything has been working great. But today I made a new class like usual and for some reason in this class I can't access Public/Global variable from other classes. All the other classes can, but now when ever I try to make a new class I can't. How would this be fixed?
I am using Swift and Xcode 6.
Working Class:
import UIKit
import Foundation
import Parse
import CoreData
var signedIn = true
class ViewController: UIViewController {
New Class:
import UIKit
class NewClass: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
signedIn = false
}
But on signedIn = false
I get the error:
use of unresolved identifier "signedIn"
One possible issue is that your new class has a different Target or different Targets from the other one.
For example, it might have a testing target while the other one doesn't. For this specific case, you have to include all of your classes in the testing target or none of them.
Once I had this problem after renaming a file. I renamed the file from within Xcode, but afterwards Xcode couldn't find the function in the file. Even a clean rebuild didn't fix the problem, but closing and then re-opening the project got the build to work.
'Use of Unresolved Identifier' in Swift my also happen when you forgot to import a library. For example I have the error:
In which I forgot the UIKit
import UIKit
Sometimes the compiler gets confused about the syntax in your class. This happens a lot if you paste in source from somewhere else.
Try reducing the "unresolved" source file down to the bare minimum, cleaning and building. Once it builds successfully add all the complexity back to your class.
This has made it go away for me when re-starting Xcode did not work.
Another place I've seen this error is when your project has multiple targets AND multiple bridging headers. If it's a shared class, make sure you add the resource to all bridging headers.
A good tip to is to look in the left Issue Navigator panel; the root object will show the target that is issuing the complaint.
For me this error happened because I was trying to call a nested function. Only thing I had to do to have it fixed was to bring the function out to a scope where it was visible.
In my case, I had an Object-C file which was also in the same Target Membership. I fixed by adding #import "YourObjectCFileHeader.h" inside file Bridging-Header.h
Because you haven't declared it. If you want to use a variable of another class you must use
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var DestViewController : ViewController = segue.destinationViewController as ViewController
DestViewController.signedIn = false
}
You have to put this code at the end of the NewClass code
Your NewClass inherits from UIViewController. You declared signedIn in ViewController. If you want NewClass to be able to identify that variable it will have to be declared in a class that your NewClass inherits from.
I got this error for Mantle Framework in my Objective-Swift Project.
What i tried is ,
Check if import is there in Bridging-Header.h file
Change the Target Membership for Framework in Mantle.h file as shown in below screenshot.
Toggle between Private Membership first build the project , end up with errors.
Then build the project with Public Membership for all the frameworks appeared for Mantle.h file, you must get success.
It is just a bug of building with multiple framework in Objective-C Swift project.
If this is regarding a class you created, be sure that the class is not nested.
F.e
A.swift
class A {
class ARelated {
}
}
calling var b = ARelated() will give 'Use of unresolved identifier: ARelated'.
You can either:
1) separate the classes if wanted on the same file:
A.swift
class A {
}
class ARelated {
}
2) Maintain your same structure and use the enclosing class to get to the subclass:
var b = A.ARelated
I did a stupid mistake. I forgot to mention the class as public or open while updating code in cocoapod workspace.
Please do check whether accesor if working in separate workspace.
You forgot to declare the variable. Just put var in front of signedIn = false
My issue was calling my program with the same name as one of its cocoapods. It caused a conflict. Solution: Create a program different name.
This is not directly to your code sample, but in general about the error. I'm writing it here, because Google directs this error to this question, so it may be useful for the other devs.
Another use case when you can receive such error is when you're adding a selector to method in another class, eg:
private class MockTextFieldTarget {
private(set) var didCallDoneAction = false
#objc func doneActionHandler() {
didCallDoneAction = true
}
}
And then in another class:
final class UITextFieldTests: XCTestCase {
func testDummyCode() {
let mockTarget = MockTextFieldTarget()
UIBarButtonItem(barButtonSystemItem: .cancel, target: mockTarget, action: MockTextFieldTarget.doneActionHandler)
// ... do something ...
}
}
If in the last line you'd simply call #selector(cancelActionHandler) instead of #selector(MockTextFieldTarget.cancelActionHandler), you'd get
use of unresolved identifier
error.

IBDesignable Errors When Adding to Tests Target

I have a simple UIButton subclass that implements IBDesignable with an IBInspectable var:
#IBDesignable class Button: UIButton {
#IBInspectable var borderColor: UIColor = UIColor.whiteColor() {
didSet { layer.borderColor = borderColor.CGColor }
}
}
I am not using this within a framework and it is working in Interface Builder as intended, however, once I add this subclass to my Tests target, it stops rendering live and I get the following errors:
Main.storyboard: error: IB Designables: Failed to update auto layout status: dlopen(TestTests.xctest, 1): Library not loaded: #rpath/XCTest.framework/XCTest
Referenced from: TestTests.xctest
Reason: image not found
Main.storyboard: error: IB Designables: Failed to render instance of Button: dlopen(TestTests.xctest, 1): Library not loaded: #rpath/XCTest.framework/XCTest
Referenced from: TestTests.xctest
Reason: image not found
If I remove IBDesignable and the IBInspectable vars, the errors go away - unfortunately so does the live rendering in Interface Builder.
How do I test against an IBDesignable class without these errors?
At first, I thought this was a kind of bug in Xcode. Following is the workaround I found:
STEP 1
Mark your class and properties as public.
#IBDesignable public class Button: UIButton {
#IBInspectable public var borderColor: UIColor = UIColor.whiteColor() {
didSet { layer.borderColor = borderColor.CGColor }
}
#IBInspectable public var borderWidth:CGFloat = 0.0 {
didSet { layer.borderWidth = borderWidth }
}
}
STEP 2
Import your application module from your "Tests" module.
For example, assuming that your application is named MyGreatApp, in your MyGreatAppTests/MyGreatAppTests.swift:
import UIKit
import XCTest
import MyGreatApp
class MyGreatAppTests: XCTestCase {
func testExample() {
let btn = Button()
btn.borderColor = UIColor.redColor()
XCTAssertEqual(UIColor(CGColor:btn.layer.borderColor), UIColor.redColor(), "borderColor")
}
}
You don't need to add 'Button.swift' to your "Tests" target.
STEP 3 (for Swift)
In your storyboard explicitly select the module MyGreatApp for any custom classes instead of letting Xcode use the current module.
Your question describes exactly the circumstances I experienced.
The error is also visible in the attribute inspector under your own attributes.
This is the workaround that worked for me:
Step 1
remove all #IBDesignable and #IBInspectable from your source code
Step 2
Go back to the interface builder. The error is still there.
Step 3
Restart XCode, rebuild your project.
Errors should be vanished.
Step 4
add all #IBDesignable and #IBInspectable again to your source code
After this steps I was able to go on with my project without any problems.
My theory why this works is that the interface builder caches some stuff that is not deleted (and rebuilt later) when you do a Project -> Clean.
The other answer (Importing your main module into your test module) is a good idea and solved some nasty problems for me in the past but not this one.
The solution is very simple. You need to remove your test target, and create it once again from the start. When I had moved the project to Xcode 7, I got an warning that my test target is damaged. So I decided to set it up once again. IT WORKED!.
Additionally you do not attach your storyboards and not even any class to your test target. Please do not do it like this:
Instead, do it this way:
So, simply remove any file from your test target (including classes with #IBDesignables), then If you need access to your classes within your test target just use #testable import MyApp:
It is working and every errors with IBDesignables will disappear. Enjoy:-)
What is causing this?
This error appears when two things happen:
You include any file containing #IBDesignable or #IBInspectable in your test target.
You open your .storyboard or .xib file (containing your designable/inspectable views).
How can I prevent this from happening?
Either:
Don’t include files containing #IBDesignable or #IBInspectable in your test target. (If you’re just testing a few isolated model files, they can remain members of your test target.)
Remove all of your app’s files from your test target (as illustrated in Bartłomiej's answer), and instead import your app’s module into your test file (e.g. #testable import MyApp—see here for more details.) This is the best practice, allowing you to continue testing your designable/inspectable views as well as any model code in your app.
How can I solve it once it's already happened?
The pesky thing with this error is that it doesn’t automatically go away once the problem has been solved, potentially because IB may be caching something as Gerd suggests in his answer.
What I’ve found is that once you’ve actually performed either of the two preventative measures I listed above, simply restarting Xcode (without modifying any code) should make the error go away.
I finally found the solution. Juste add "-framework XCTest" to your test target under Build Settings / other linker flags.
This issue can also be caused by including any categories or extensions on the view class in your test target.

Resources