How to disappear sidemenu without button in swift 4
I have some question. i made side menu in swift4.
when i clicked button, side menu appear and disappear.
but i want make disappear side menu without button.
for example, when i clicked another view (not side menu), disappear sidemenu.
my code like this.
class ContainerVC: UIViewController {
@IBOutlet weak var constaint: NSLayoutConstraint!
var sideMenuOpen = false
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(toggleSideMenu), name: NSNotification.Name("ToggleSideMenu"), object: nil)
}
@objc func toggleSideMenu(){
if sideMenuOpen {
sideMenuOpen = false
constaint.constant = -130
}else {
sideMenuOpen = true
constaint.constant = 0
}
UIView.animate(withDuration: 0.3){
self.view.layoutIfNeeded()
}
}
when i click white background (view) , disappear side menu. Thanks.
1 answer
-
answered 2018-04-17 06:21
aBilal17
You can use code something like that, please add following code in viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss(fromGesture:))) self.view.addGestureRecognizer(tap)
Then create a function for dismiss
@objc func OpenSideMenu(){ sideMenuOpen = true constaint.constant = 0 UIView.animate(withDuration: 0.3){ self.view.layoutIfNeeded() } } @objc func closeSideMenu(){ sideMenuOpen = false constaint.constant = -130 UIView.animate(withDuration: 0.3){ self.view.layoutIfNeeded() } } @objc func dismiss(fromGesture gesture: UISwipeGestureRecognizer) { closeSideMenu() }
Hope this will work.
See also questions close to this topic
-
UITableViewCell - drag whole row to move?
I'm trying to use a
UITableViewController
and allow the user to reorganize my data by dragging the rows. This is working fine, except that the user has to tap on the relatively smallUITableViewCellReorderControl
on the right quarter of the cell to drag the row.Here's an example:
As far as I can tell there's no way to get ahold of the
UITableViewCellReorderControl
or access its size or behavior through theUITableViewDelegate
. Is there a way to customize drag behavior so that you can drag anywhere on the cell to move it up or down? -
HTML Input autocomplete not working in WKWebview
Inputs with autocomplete enabled are working properly when opening in mobile Safari but not when loaded in a
WKWebview
(iOS 11.3). Is this a known limitation? -
Enterprise Distribution iPhone requirements
We're trying to make an application using Enterprise Distribution (Because we don't want the application to be reviewed by Apple or available on the App Store) for some contractors of the company. They're not employees per se, and as such, their iPhones are not company issued, they are their own personal phones.
The point is:
- Can they install the application without issues?
- Do their phones have to met some requisites before installation?
I've read a lot of conflicting answers online and I'm not sure. Some people say that the UDID of their phones will be required to add them to some "list", others say that if their phones are not company issued they cannot install it, and others say that they will be able to install it, but just have to add the company to the trusted manufacturers.
I have even sent this question to Apple support and they just answered with:
The Apple Developer Enterprise Program is intended for a company to create proprietary apps designed and distributed exclusively to their organization’s employee. A company wanting to distribute to staff that are not direct employees would not meet program requirements.
Which is not what it seems in the hundreds of pages I've visited.
Thanks in advance.
-
Given a timestamp (string), how do I find the closest timestamp within a NSTextView and scroll to it. The exact timestamp may not exist
I have a NSTextView that displays a log (15+ mb worth of text). There will be timestamps in the log. Example snippet:
2018-04-22 07:54:49 <Homebound> [tests > ... Ending 2018-04-22 07:54:49 <Homebound> [tests > ... Starting launchctl load /System/Library/ 2018-04-22 07:54:50 (null)
I have a dropdown menu with time stamps. Timestamps are strings with this format:
2018-04-22 07:54:49
Currently I am able to select a time stamp from the drop down menu and find the timestamp within the NSTextView and scroll to where the timestamp is. Here is the code:
let haystack = myTextBox.string var needle = failuresArray[selectedIndex - 1][3] needle.removeLast(2) // (needle would like like: 2018-04-22 07:54) if let needleRange = haystack.range(of: needle) { myTextBox.scrollRangeToVisible(NSRange(needleRange, in: haystack)) }
Problem I am encountering is that the exact timestamp may not be in the log that is displayed in the NSTextView. How do I find the closest timestamp within the NSTextView and scroll to it?
-
Showing Images on Button through IF Statement
I'm new to swift and the iOS platform in general, but I think I have a decent grasp on it.
I'm attempting to make a simple Bingo game, but I've run into a little issue.
I need to give the user the ability to deselect a number. Right now, I've got buttons that the user will click on to to change that piece to marked (giving it a background image). However, I want to change the image to nothing if they press the button again.
For the life of me, I can't seem to figure out how to check, preferably with an IF statement, whether the button has been pressed the first time or not. I was trying to use an IF statement to compare the image with something like this:
@IBAction func action(_ sender: AnyObject) { if UIImage(named:"MarkedPiece") == true { // labels for Numbers will be hidden here } else { sender.setImage(UIImage(named: "MarkedPiece"), for: UIControlState()) } }
The above is the function that all of the buttons point to. I get the error message telling me that I can't compare type UIImage to BOOL, which makes sense. Is there another way that I should do it?
Any help would be appreciated!
-
return data from class (ios)
i have a
api
where i take data from my server and i have function inmy class
i havefunc getall
which returns the data after take and parsing. At the end of the function I writereturn data
. I used debugging, and saw that the data inside the class is being filled, only I do not really understand if I can return this data from the class. in myviewController
i make:
var data = [model]()
var api = api()
data = api.getall()
-
Rss Feed Parsing with Table
I am having trouble with parsing an xml rss feed. I am calling my XMLParser.swift file from my TableViewController.swift file to parse the data so I can add it to the table, but it doesn't work. The data that it returned is 0 or nil.
import UIKit import FeedKit let feedURL = URL(string: "http://www.uwbrandingiron.com/feed/")! class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, ExpandableHeaderViewDelegate { @IBOutlet weak var tableView: UITableView! private var rssItems: [RSSItem] = [] var sections = [ Section(grouping: "Branding Iron Online", links: [], expanded: false), Section(grouping: "Podcasts", links: [RSSItem(title:"Coming Soon",link:"")], expanded: false), Section(grouping: "OneTV", links: [RSSItem(title:"OneTV Channel",link:"https://www.youtube.com/channel/UCy-Hcyj83bMHRVlPeVSssLg")], expanded: false), Section(grouping: "Frontiers", links: [RSSItem(title:"Coming Soon",link:"")], expanded: false) ] override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 155.0 tableView.rowHeight = UITableViewAutomaticDimension fetchData() /* if(rssItems.count==0) { print("Parse failed") }else { sections.append(Section(grouping: "Branding Iron Online", links: rssItems, expanded: false)) } */ addData() } private func addData() { print("The total size in TableViewControll is ", rssItems.count) sections.append(Section(grouping: "Branding Iron Online", links: rssItems, expanded: false)) } private func fetchData() { let feedParser = FeedParser() feedParser.parseFeed(url: "http://www.uwbrandingiron.com/feed/") { (rssItems) in self.rssItems = rssItems OperationQueue.main.addOperation { self.tableView.reloadSections(IndexSet(integer: 0), with: .left) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { return sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //return rssItems.count return sections[section].links.count } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if (sections[indexPath.section].expanded) { return 44 } else { return 0 } } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 2 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = ExpandableHeaderView() header.customInit(title: sections[section].grouping, section: section, delegate: self) return header } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "labelCell")! /* if let item = rssItems?[indexPath.item] { cell.item = item } */ cell.textLabel?.text = sections[indexPath.section].links[indexPath.row].title return cell } func toggleSection(header: ExpandableHeaderView, section: Int) { sections[section].expanded = !sections[section].expanded tableView.beginUpdates() for i in 0 ..< sections[section].links.count { tableView.reloadRows(at: [IndexPath(row: i, section: section)], with: .automatic) } tableView.endUpdates() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let webController = WebViewController() if(sections[indexPath.section].links[indexPath.row].link == "") { tableView.deselectRow(at: indexPath, animated: true) } else { webController.customInit(link: sections[indexPath.section].links[indexPath.row].link) tableView.deselectRow(at: indexPath, animated: true) self.navigationController?.pushViewController(webController, animated: true) } } }
Here is my parser.
import Foundation struct RSSItem { var title: String var link: String } class FeedParser: NSObject, XMLParserDelegate { private var rssItems: [RSSItem] = [] private var currentElement = "" private var currentTitle: String = "" { didSet { currentTitle = currentTitle.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } private var currentLink: String = "" { didSet { currentLink = currentLink.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } private var parserCompletionHandler: (([RSSItem]) -> Void)? func parseFeed(url: String, completionHandler:(([RSSItem]) -> Void)?) { self.parserCompletionHandler = completionHandler let request = URLRequest(url: URL(string: url)!) let urlSession = URLSession.shared let task = urlSession.dataTask(with: request) { (data,response, error) in guard let data = data else { if let error = error { print(error.localizedDescription) } return } // parse our xml data let parser = XMLParser(data: data) parser.delegate = self parser.parse() } task.resume() } //MARK: -XML PArser Delegate func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { currentElement = elementName if currentElement == "item" { currentTitle = "" currentLink = "" } } func parser(_ parser: XMLParser, foundCharacters string: String) { switch currentElement { case "title": currentTitle += string case "link": currentLink += string default: break } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if elementName == "item" { let rssItem = RSSItem(title: currentTitle, link: currentLink) self.rssItems.append(rssItem) } } func parserDidEndDocument(_ parser: XMLParser) { print("The total size is ",rssItems.count) print("End of document") parserCompletionHandler?(rssItems) } func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { print(parseError.localizedDescription) } }
I have two areas of print testing one with the parser in the function parserDidEndDocument and the other in the table in the addData function. The order of the printed statements is the addData one first, which I find to be weird, and the parserDidEndDocument second. The first one says size is 0, while the other says size is 10.
-
Can't show more than one option to UIMenuController
I want to make a longPress to a message and show two options in UIMenuController
Delete and Copy
but only Copy is showing
@objc func longPressLabel(sender: AnyObject?) { becomeFirstResponder() let copyMenuItem = UIMenuItem(title: “Copy”.localized, action: #selector(copyTapped)) let deleteMenuItem = UIMenuItem(title: “Delete”.localized, action: #selector(deleteTapped)) let menu = UIMenuController.shared menu.arrowDirection = UIMenuControllerArrowDirection.down menu.setTargetRect(bounds, in: self) menu.menuItems = [copyMenuItem, deleteMenuItem] menu.setMenuVisible(true, animated: true) }
Also If I delete all UIMenuItems and I make a empty menu this show me a copy option, it's like it's showing a template and not the options I add
I'm using IOS 11.1 and Swift4.1
Here is an Example
-
Codename One material command in side menu malfunctioning
I have an Android application that uses the sidemenu. When I add a material command to the side menu, the command does not execute the code associated to it.
In the simulator, I have to press the material command several times before it reacts properly. On the installed device, the material command dos not work at all.
Command seems to work and adding a button to the sidemenu works normally.
Here is my code:
toolbar.addMaterialCommandToSideMenu("Home", FontImage.MATERIAL_HOME, e -> { System.out.println("home"); form.removeAll(); toolbar.removeAll(); hi.start(); });
-
Ionic 2/3 - How to keep a side menu open until the user clicks on a given button?
Is there a way to keep an Ionic 3 side menu open until the user clicks on a given button?
The default behavior is that a side menu closes itself when the ion-content associated with receives a click event. I would like to override this behavior.
<ion-menu type="push" (ionClose)="execDirtyWay()" [content]="dahcontent"> <!-- I need this menu to stay open --> <!-- Even if the user clicks on the below ion-content --> </ion-menu> <ion-content #dahcontent> <!-- my content is here --> </ion-content>
I'm using a push menu that displays a list and I need my ion-content area to be clickable without closing the said menu.
My issue is the same as this but I found none of the answers to be satisfying.
For now, I found a very dirty way to kinda get what I need:
in the
ionClose
event of the menu, I reopen it 。(^▽^)ゞ