How to hide the second uibaritem in swift 2 - swift2

I have 2 bar items as shown below how can I hide the second one when I click on the first one ? ( i tried earthBtn.hidden = true but its not working. Here is my code:
let earthImg = UIImage(named: "earth0")
let earthBtn = UIBarButtonItem(image: earthImg, style: .Plain, target: self, action: "earthBtn_click")
let messageImg = UIImage(named: "categories1")
let messageBtn = UIBarButtonItem(image: messageImg, style: .Plain, target: self, action: "messageBtn_click")
let buttonArray = NSArray(objects: earthBtn,messageBtn)
self.navigationItem.rightBarButtonItems = buttonArray as? [UIBarButtonItem]
func messageBtn_click() {
earthBtn.hidden = true // is not working
}
thank you.

Alright, you cannot hide a UIBarButtonItem and what you can do is make the color transparent and disable it, and when you wanna use it back then you have to enable it and then give it a color:
Define it globally as class variable :
let earthBtn = UIBarButtonItem()
Use it like :
earthBtn = UIBarButtonItem(image: earthImg, style: .Plain, target: self, action: "earthBtn_click")
hide the button:
func messageBtn_click() {
earthBtn.enabled = false
earthBtn.color = UIColor.clearColor()
}

Related

Image on tabItem, UIKit UITabBarController

Hi im making an app with uikit and i want to set a profile image(received from url) on Tabbar item. I am expecting the updated profile image on TabBarItem. Also i want to add a border around the image when the tab is selected.
I found this solution, but the image does not appear in the tabitem.
Set user's profile picture on Tabbar item
extension UITabBarController {
func addSubviewToLastTabItem(_ image: UIImage) {
if let lastTabBarButton = self.tabBar.subviews.last, let tabItemImageView = lastTabBarButton.subviews.first {
if let accountTabBarItem = self.tabBar.items?.last {
accountTabBarItem.selectedImage = nil
accountTabBarItem.image = nil
}
let imgView = UIImageView()
imgView.frame = tabItemImageView.frame
imgView.layer.cornerRadius = tabItemImageView.frame.height/2
imgView.layer.masksToBounds = true
imgView.contentMode = .scaleAspectFill
imgView.clipsToBounds = true
imgView.image = image
self.tabBar.subviews.last?.addSubview(imgView)
}
}
}
Could someone help me to do that?
Did you add the second part of code:
let yourImage = UIImage(named: "your-image")
override func viewDidLayoutSubviews() { // add to any vc
super.viewDidLayoutSubviews()
tabBarController?.addSubviewToLastTabItem(yourImage)
}
When you call addSubviewToLastTabItem("String") it is critical print correctly parameter without mistakes.
Could you post this part of code?
One more thing viewDidLayoutSubviews will work if you rotate iPhone, double check please that you are calling addSubviewToLastTabItem() in viewDidLoad()

How to use an array to fill the title text

I've created a customized keyboard using UIView. I'm trying to auto-fill the letters using a for loop but with no success.
func initializeSubviews() {
let xibFileName = "keyboardView" // xib extension not included b
let view = Bundle.main.loadNibNamed(xibFileName, owner: self, options: nil)![0] as! UIView
self.addSubview(view)
view.frame = self.bounds
setKeyboardText()
}
#IBOutlet var keyboardLetters: [myKeyboardBtn]!
func setKeyboardText() {
let str = "abcdefghijklmnopqrstuvwxyz"
let characterArray = Array(str)
for (Index, key) in keyboardLetters.enumerated() {
key.titleLabel?.text = String(characterArray[Index])
}
// [a,b,c,d,...]
}
what am I doing wrong?
According to Apple
"To set the actual text of the label, use setTitle(_:for:)
(button.titleLabel.text does not let you set the text)."

How can I rename label with another class attribute?

So, here is the part of class OnboardingViewController, where declared and initialized reviewConsentStep.
class OnboardingViewController: UIViewController {
// MARK: IB actions
#IBAction func joinButtonTapped(sender: UIButton) {
let consentDocument = ConsentDocument()
let consentStep = ORKVisualConsentStep(identifier: "VisualConsentStep", document: consentDocument)
let healthDataStep = HealthDataStep(identifier: "Health")
let signature = consentDocument.signatures!.first!
let reviewConsentStep = ORKConsentReviewStep(identifier: "ConsentReviewStep", signature: signature, inDocument: consentDocument)
reviewConsentStep.text = "Review the consent form."
reviewConsentStep.reasonForConsent = "Consent to join the Developer Health Research Study."
let passcodeStep = ORKPasscodeStep(identifier: "Passcode")
passcodeStep.text = "Now you will create a passcode to identify yourself to the app and protect access to information you've entered."
let completionStep = ORKCompletionStep(identifier: "CompletionStep")
completionStep.title = "Welcome aboard."
completionStep.text = "Thank you for joining this study."
let orderedTask = ORKOrderedTask(identifier: "Join", steps: [consentStep, reviewConsentStep, healthDataStep, passcodeStep, completionStep])
let taskViewController = ORKTaskViewController(task: orderedTask, taskRunUUID: nil)
taskViewController.delegate = self
presentViewController(taskViewController, animated: true, completion: nil)
}
I want to use reviewConsentStep.signature?.givenName and reviewConsentStep.signature?.familyName here:
#IBOutlet var applicationNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
applicationNameLabel.text = reviewConsentStep.signature?.givenName/////////... here
If it possible, please tell me how can I do it?

Unrecognized selector sent to instance when using UIPanGesture

Hi I am trying to add UIPanGestureRecognizer to UIImageView (in my case, it's an emoji). All other UIGestureRecognizers such as long press, rotation, and pinch work well. However, it gives me an error: unrecognized selector sent to instance when I add UIPanGestureRecognizer. I've spent a day trying to figure out the reason but failed to fix it. Please help! Thanks in advance.
This is a function where I added UIGestureRecognizer to sticker
func emojiInsert(imageName: String) {
deleteButtonHides()
let stickerView: UIImageView = UIImageView(frame: CGRectMake(backgroundImage.frame.width/2 - 50, backgroundImage.frame.height/2 - 50, stickerSize, stickerSize))
stickerView.image = UIImage(named: imageName)
stickerView.userInteractionEnabled = true
stickerView.accessibilityIdentifier = "sticker"
let deleteStickerButton: UIImageView = UIImageView(frame: CGRectMake(stickerView.frame.width - 5 - stickerView.frame.width/3, 5, stickerView.frame.width/3, stickerView.frame.height/3))
deleteStickerButton.image = UIImage(named: "button_back")
deleteStickerButton.accessibilityIdentifier = "delete"
deleteStickerButton.userInteractionEnabled = true
deleteStickerButton.alpha = 0
deleteStickerButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "deleteButtonTouches:"))
stickerView.addSubview(deleteStickerButton)
stickerView.addGestureRecognizer(UIPinchGestureRecognizer(target: self, action: "handlePinch:"))
stickerView.addGestureRecognizer(UIRotationGestureRecognizer(target: self, action: "handleRotate:"))
stickerView.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: "handleLongPress:"))
stickerView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "handlePan"))
print("emojiInsert : \(imageName)")
backgroundImage.addSubview(stickerView)
}
Below are call back functions I added in the end of the view.swift. I used touchesbegan and touchesMoved to drag an emoji but emoji moved in weird way after rotation. So now I am trying to use UIPanGesture to drag an emoji.
#IBAction func handlePinch(recognizer : UIPinchGestureRecognizer) {
if(deleteMode) {
return
}
print("handlePinch \(recognizer.scale)")
if let view = recognizer.view {
view.transform = CGAffineTransformScale(view.transform,
recognizer.scale, recognizer.scale)
recognizer.scale = 1
}
}
#IBAction func handleRotate(recognizer : UIRotationGestureRecognizer) {
if(deleteMode) {
return
}
if let view = recognizer.view {
view.transform = CGAffineTransformRotate(view.transform, recognizer.rotation)
recognizer.rotation = 0
}
}
#IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
if(deleteMode) {
return
}
let translation = recognizer.translationInView(self.view)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPointZero, inView: self.view)
}
#IBAction func handleLongPress(recognizer: UILongPressGestureRecognizer) {
if(recognizer.state == UIGestureRecognizerState.Began) {
if(!deleteMode) {
print("LongPress - Delete Shows")
for (_, stickers) in self.backgroundImage.subviews.enumerate() {
for (_, deleteButtons) in stickers.subviews.enumerate() {
if let delete:UIImageView = deleteButtons as? UIImageView{
if(delete.accessibilityIdentifier == "delete") {
delete.alpha = 1
}
}
}
}
deleteMode = true
} else {
deleteButtonHides()
}
}
}
Again, please help! Thanks in advance.
The problem is that you're missing a colon. In the following line:
stickerView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "handlePan"))
The handlePan should be handlePan:. That's because the Objective-C signature for your method is:
- (void)handlePan:(UIPanGestureRecognizer *)recognizer
The colon is part of the method name.

Swift "Thread 1: EXC_BAD_INSTRUCTION(code=EXC-I386_INVOP,subcode=0x0)" when using keyBoardWillShow

I am trying to let a user click on a cell in a tale view and it brings them to the DetailViewController. The only problem is that each time I try to do this the error "Thread 1: EXC_BAD_INSTRUCTION(code=EXC-I386_INVOP,subcode=0x0)" comes up.
This is in the DetailViewController:
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
//FIRST ERROR HERE
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
//SECOND ERROR HERE
/* Setup the contentInsets */
self.tableView.contentInset = UIEdgeInsetsZero
self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero
self.edgesForExtendedLayout = UIRectEdge.None
/* Make sure the content doesn't go below tabbar/navbar */
self.extendedLayoutIncludesOpaqueBars = true
self.automaticallyAdjustsScrollViewInsets = false
/* Setup Map */
let geo = party?.objectForKey("location") as PFGeoPoint
//THIRD ERROR HERE
let coordinate = CLLocationCoordinate2D(latitude: geo.latitude, longitude: geo.longitude)
let reg = MKCoordinateRegionMakeWithDistance(coordinate, 1500, 1500)
self.mapView.setRegion(reg, animated: true)
self.mapView.showsUserLocation = true
if(party?.objectForKey("comments") != nil) {
comments = party?.objectForKey("comments") as? [String]
}
println(party)
println(party?.objectForKey("Name"))
self.nameLabel.text = party?.objectForKey("Name") as? String
// Do any additional setup after loading the view.
}
The other issue is that even after I put // in front of keyBoardWillShow the same error happens for keyBoardWillHide. And if I cover that I get once again the same error trying to setup a map view. As you can probably see, I am just getting into swift, xcode, and Parse and I have no idea what I really and doing. Any help is appreciated.

Resources