I have two button namely programs and data.This two button have drop down option.But when i select the first drop down option for program and if i select any data from drop down .say like i select "super" from drop down .Then that super word are selecting in my both button.
With out selecting my second button drop down option.Its automatically changing.For clearly, if i select super data from drop down for program button,That word "super" is updating in my both drop down button.
Please help me to fix this problem :
Here is my code:
import UIKit
class UserDetailsController: UIViewController {
var addString: String!
let dropDown = DropDown()
#IBOutlet weak var programBtn: UIButton!
#IBOutlet weak var dataBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
dropdownmethod()
}
func dropdownmethod () {
dropDown.dataSource = [
"Car",
"Motorcycle",
"Van",
"Truck",
"Bus",
"Bicycle",
"Feet",
"add"
]
dropDown.selectionAction = { [unowned self] (index, item) in
self.SpectifBtn.setTitle(item, forState: .Normal)
self.organBtn.setTitle(item, forState: .Normal)
if item == "add" {
if #available(iOS 8.0, *) {
let alert = UIAlertController(title: "Duplicate file", message: "Afile with the same name already exists.", preferredStyle:
UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler(self.configurationTextField)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
print("User click Ok button")
print(self.textField.text)
self.addString = self.textField.text
self.dropDown.dataSource = [ "Car",
"Motorcycle",
"Van",
"Truck",
"Bus",
"Bicycle",
"Feet", "\(self.addString)", "add"]
self.SpectifBtn.setTitle(self.addString, forState: .Normal)
self.organBtn.setTitle(self.addString, forState: .Normal)
}))
self.presentViewController(alert, animated: true, completion: {
print("completion block")
})
} else {
// Fallback on earlier versions
}
}
}
dropDown.cancelAction = { [unowned self] in
self.dropDown.selectRowAtIndex(0)
self.SpectifBtn.setTitle("Canceled", forState: .Normal)
self.organBtn.setTitle("Canceled", forState: .Normal)
}
dropDown.anchorView = SpectifBtn
dropDown.bottomOffset = CGPoint(x: 0, y:SpectifBtn.bounds.height)
dropDown.dismissMode = .Automatic
dropDown.selectRowAtIndex(3)
}
func configurationTextField(textField: UITextField!)
{
if let aTextField = textField {
textField.text = "Filename"
self.textField = aTextField
}
}
#IBAction func programBtnPressed(sender: AnyObject) {
if dropDown.hidden {
dropDown.show()
} else {
dropDown.hide()
}
}
#IBAction func dataBtnPressed(sender: AnyObject) {
if dropDown.hidden {
dropDown.show()
} else {
dropDown.hide()
}
}
}
My screen shot.When i select any option from my program drop down.That option name is automatically updating in my data button name also
After dropdown selection of some item, you should check from what button it comes(by tag for example), now it seems you just select them both here:
self.SpectifBtn.setTitle(item, forState: .Normal) self.organBtn.setTitle(item, forState: .Normal)
Related
I'm trying to show a UIAlertController over a UIButton. The button is of type custom, and I have set the tint color to UIColor.clear, because I don't want any tint color. I've read that setting your UIButton to custom turns off the tint color, but that doesn't work for me. This method works out ok, until I show an alert controller on top.
This is before adding the alert:
This is what it looks like when I show the alert:
There's a clear grey tint color around the UIButton. It does this with any .selected UIButtons. How do I get rid of this tint? I really don't want to make my own button class just to get rid of this.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var starBtn: UIButton!
var selected: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
starBtn.isSelected = selected
starBtn.setImage(UIImage(named: "StarButtonSelected"), for: .selected)
starBtn.setImage(UIImage(named: "StarButtonDeselected"), for: .normal)
starBtn.isHighlighted = false
starBtn.tintColor = UIColor.clear
starBtn.backgroundColor = UIColor.clear
}
#IBAction func starBtnUp(_ sender: Any) {
selected = !selected
starBtn.isSelected = selected
}
#IBAction func showAlertBtnUp(_ sender: Any) {
let shareFileAction = UIAlertAction(title: "Share File", style: .default) { action in
}
let shareWebLink = UIAlertAction(title: "Share Link", style: .default) { action in
}
let alert = UIAlertController(title: "Share", message: "What do you want to share?", preferredStyle: .alert)
alert.addAction(shareFileAction)
alert.addAction(shareWebLink)
self.present(alert, animated: true) {
}
}
}
Edit: Okay, so if I create the button programmatically only, without using IB, it doesn't do the grey tint thing. I really don't want to have to not use IB though. Here's the re-written code that works how I want it to.
class ViewController: UIViewController {
var starBtn: UIButton!
var selected: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
starBtn = UIButton(type: .custom)
self.view.addSubview(starBtn)
starBtn.translatesAutoresizingMaskIntoConstraints = false
starBtn.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
starBtn.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
starBtn.heightAnchor.constraint(equalToConstant: 60).isActive = true
starBtn.widthAnchor.constraint(equalToConstant: 60).isActive = true
starBtn.isSelected = selected
starBtn.tintColor = UIColor.clear
starBtn.setImage(UIImage(named: "StarButtonSelected"), for: .selected)
starBtn.setImage(UIImage(named: "StarButtonDeselected"), for: .normal)
starBtn.isHighlighted = false
starBtn.backgroundColor = UIColor.clear
starBtn.addTarget(self, action: #selector(starBtnUp(_:)), for: .touchUpInside)
}
#IBAction func starBtnUp(_ sender: Any) {
selected = !selected
starBtn.isSelected = selected
}
#IBAction func showAlertBtnUp(_ sender: Any) {
let shareFileAction = UIAlertAction(title: "Share File", style: .default) { action in
}
let shareWebLink = UIAlertAction(title: "Share Link", style: .default) { action in
}
let alert = UIAlertController(title: "Share", message: "What do you want to share?", preferredStyle: .actionSheet)
alert.addAction(shareFileAction)
alert.addAction(shareWebLink)
self.present(alert, animated: true) {
}
}
}
I am using this library https://github.com/kciter/Floaty, I have a tab bar and in the middle I put the Floaty button
It looks like this:
However the hit area of the floaty button is way too big that I cannot tap the tab bar items on the right
Like this:
Code:
import UIKit
import Floaty
class TabBarController: UITabBarController, FloatyDelegate {
var floaty = Floaty()
override func viewDidLoad() {
super.viewDidLoad()
layoutFAB()
//floaty.addDragging()
}
#IBAction func endEditing() {
view.endEditing(true)
}
func layoutFAB() {
let item = FloatyItem()
item.hasShadow = false
item.buttonColor = UIColor.blue
item.circleShadowColor = UIColor.red
item.titleShadowColor = UIColor.blue
item.titleLabelPosition = .right
item.title = "titlePosition right"
item.handler = { item in
}
floaty.hasShadow = false
floaty.addItem(title: "I got a title")
floaty.addItem("I got a icon", icon: UIImage(named: "icShare"))
floaty.addItem("I got a handler", icon: UIImage(named: "icMap")) { item in
let alert = UIAlertController(title: "Hey", message: "I'm hungry...", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Me too", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
floaty.addItem(item: item)
floaty.paddingX = self.view.frame.width/2 - floaty.frame.width/2
floaty.paddingY = 44
floaty.buttonColor = #colorLiteral(red: 0.986409843, green: 0.4042935669, blue: 0.4366002679, alpha: 1)
floaty.plusColor = .white
floaty.fabDelegate = self
floaty.backgroundColor = .red
self.view.addSubview(floaty)
}
// MARK: - Floaty Delegate Methods
func floatyWillOpen(_ floaty: Floaty) {
print("Floaty Will Open")
}
func floatyDidOpen(_ floaty: Floaty) {
print("Floaty Did Open")
}
func floatyWillClose(_ floaty: Floaty) {
print("Floaty Will Close")
}
func floatyDidClose(_ floaty: Floaty) {
print("Floaty Did Close")
}
}
Any thoughts please? Thank you
You are using padding, adding space between frame of the button and its content. This is why the whole box is still counts as hit area. Try changing the position of the button, not padding. Floaty is a UIView subclass after all.
I am trying to add UILabels and other UIView elements on button press and have them act as independent elements but I am having no luck. I can successfully add multiple labels and text fields but when i try to delete them using my gesture recognizer it will only delete the latest UIView element. My full code is posted below. There are two main bugs in my implementation as it is: Creating more than one label or text field at a time causes the gestures to not respond and I can only delete the latest UIView element. Any help is greatly appreciated!
My Model:
import Foundation
import UIKit
class QuizItem: UIViewController{
var alert = UIAlertController()
var labelCountStepper = 0
var tfCountStepper = 0
let gestureRecog = myLongPress(target: self, action: #selector(gestureRecognized(sender:)))
let moveGesture = myPanGesture(target: self, action: #selector(userDragged(gesture:)))
func createLabel(){
var randLabel = UILabel(frame: CGRect(x: 200, y: 200, width: 300, height: 20))
randLabel.isUserInteractionEnabled = true
randLabel.textColor = UIColor .black
randLabel.text = "I am a Test Label"
randLabel.tag = labelCountStepper
gestureRecog.quizItem = randLabel
moveGesture.quizItem = randLabel
randLabel.addGestureRecognizer(self.longPressGesture())
randLabel.addGestureRecognizer(self.movePanGesture())
topViewController()?.view.addSubview(randLabel)
labelCountStepper = labelCountStepper+1
}
func createTextField(){
var randTextField = UITextField(frame: CGRect(x: 200, y: 200, width: 300, height: 35))
randTextField.isUserInteractionEnabled = true
randTextField.backgroundColor = UIColor .lightGray
randTextField.placeholder = "Enter your message..."
randTextField.tag = tfCountStepper
gestureRecog.quizItem = randTextField
moveGesture.quizItem = randTextField
randTextField.addGestureRecognizer(self.longPressGesture())
randTextField.addGestureRecognizer(self.movePanGesture())
topViewController()?.view.addSubview(randTextField)
tfCountStepper = tfCountStepper+1
}
func longPressGesture() -> UILongPressGestureRecognizer {
let lpg = UILongPressGestureRecognizer(target: self, action: #selector(gestureRecognized(sender:)))
lpg.minimumPressDuration = 0.5
return lpg
}
func movePanGesture() -> UIPanGestureRecognizer {
let mpg = UIPanGestureRecognizer(target: self, action: #selector(userDragged(gesture:)))
return mpg
}
#objc func gestureRecognized(sender: UILongPressGestureRecognizer){
if(sender.state == .began){
print("Label Tag #: \(labelCountStepper)")
print("Text Field Tag #: \(tfCountStepper)")
alert = UIAlertController(title: "Remove Item?", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
self.gestureRecog.quizItem.removeFromSuperview()
}))
alert.addAction(UIAlertAction(title: "No", style: .cancel){(_) in
})
topViewController()?.present(alert, animated: true, completion: nil)
}
}
#objc func userDragged(gesture: UIPanGestureRecognizer){
let loc = gesture.location(in: self.view)
moveGesture.quizItem.center = loc
}
override func viewDidLoad() {
super.viewDidLoad()
}
func topViewController() -> UIViewController? {
guard var topViewController = UIApplication.shared.keyWindow?.rootViewController else { return nil }
while topViewController.presentedViewController != nil {
topViewController = topViewController.presentedViewController!
}
return topViewController
}
}
My ViewController:
import UIKit
class ViewController: UIViewController {
var labelMaker = QuizItem()
#IBAction func createLabel(_ sender: UIButton) {
labelMaker.createLabel()
}
#IBAction func createTextField(_ sender: UIButton) {
labelMaker.createTextField()
}
override func viewDidLoad() {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I also made two subclasses that inherit from UILongPress and UIPan Gesture Recognizers. I'll only post the LongPress because the UIPan is exactly the same - just inherits from UIPan instead of UILongPress.
import Foundation
import UIKit
class myLongPress: UILongPressGestureRecognizer{
var quizItem = UIView()
}
You can achieve that by slighting changing your code as below:
#objc func gestureRecognized(sender: UILongPressGestureRecognizer){
if(sender.state == .began){
print("Label Tag #: \(labelCountStepper)")
print("Text Field Tag #: \(tfCountStepper)")
alert = UIAlertController(title: "Remove Item?", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
let selectedView = sender.view
selectedView?.removeFromSuperview()
}))
alert.addAction(UIAlertAction(title: "No", style: .cancel){(_) in
})
topViewController()?.present(alert, animated: true, completion: nil)
}
}
#objc func userDragged(gesture: UIPanGestureRecognizer){
let loc = gesture.location(in: self.view)
let selectedView = gesture.view
selectedView?.center = loc
}
I currently have an action sheet made using SimpleAlert that generates a list of buttons. The buttons recognize taps and long presses. On the long press I am trying to pass the button as a sender through a selector in order to access the button tag in another function, however it keeps giving me this error:
2017-07-26 11:27:15.173 hitBit[8614:134456] *** Terminating app due to
uncaught exception 'NSInvalidArgumentException', reason:
'-[LongTap(sender: button]: unrecognized selector sent to instance
0x7f9c458ccc00'
How can I pass objects such as buttons through the selector? If there is a solution that allows me to just pass through an integer, that would work fine as well.
#IBAction func tapMGName(_ sender: Any) {
let mgController = MouthguardSelectionController(title: "Go to:", message: nil, style: .actionSheet)
//For every MG, make an action that will navigate you to the mouthguard selected
for i in 0...self.getNumberDevices() - 1 {
mgController.addAction(index: i, (AlertAction(title: mg_Name[i], style: .ok) { action -> Void in
self.changeMouthguard(index: i)
self.dismiss(animated: true, completion: nil)
}))
}
Code that creates the custom action sheet and generates actions for the list
override func configureButton(_ style :AlertAction.Style, forButton button: UIButton, index: Int) {
super.configureButton(style, forButton: button)
cur_mg_ID_index = index
let longGesture = UILongPressGestureRecognizer(target: self, action: "LongTap(sender: button") //Long function will call when user long press on button.
if (button.titleLabel?.font) != nil {
switch style {
case .ok:
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
button.tag = index
button.addGestureRecognizer(longGesture)
case .cancel:
button.backgroundColor = UIColor.darkGray
button.setTitleColor(UIColor.white, for: .normal)
case .default:
button.setTitleColor(UIColor.lightGray, for: .normal)
default:
break
}
}
}
func LongTap(sender: UIButton) {
print(sender.tag)
let nameChanger = AlertController(title: "Change name of ya boy", message: nil, style: .alert)
nameChanger.addTextFieldWithConfigurationHandler() { textField in
textField?.frame.size.height = 33
textField?.backgroundColor = nil
textField?.layer.borderColor = nil
textField?.layer.borderWidth = 0
}
nameChanger.addAction(.init(title: "Cancel", style: .cancel))
nameChanger.addAction(.init(title: "OK", style: .ok))
present(nameChanger, animated: true, completion: nil)
}
Code within the custom SimpleAlert action sheet
Try this and see,
override func configureButton(_ style :AlertAction.Style, forButton button: UIButton, index: Int) {
super.configureButton(style, forButton: button)
cur_mg_ID_index = index
// Edited line....
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.longTap(_:))) //Long function will call when user long press on button.
if (button.titleLabel?.font) != nil {
switch style {
case .ok:
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
button.tag = index
button.addGestureRecognizer(longGesture)
case .cancel:
button.backgroundColor = UIColor.darkGray
button.setTitleColor(UIColor.white, for: .normal)
case .default:
button.setTitleColor(UIColor.lightGray, for: .normal)
default:
break
}
}
}
// Edited line....
func longTap(_ gesture: UILongPressGestureRecognizer) {
// Edited line....
guard let sender = gesture.view as? UIButton else {
print("Sender is not a button")
return
}
print(sender.tag)
let nameChanger = AlertController(title: "Change name of ya boy", message: nil, style: .alert)
nameChanger.addTextFieldWithConfigurationHandler(){textField in
textField?.frame.size.height = 33
textField?.backgroundColor = nil
textField?.layer.borderColor = nil
textField?.layer.borderWidth = 0
}
nameChanger.addAction(.init(title: "Cancel", style: .cancel))
nameChanger.addAction(.init(title: "OK", style: .ok))
present(nameChanger, animated: true, completion: nil)
}
Below is my code. I have 9 buttons in my view whose background image is to be changed.
import UIKit
class ViewController: UIViewController {
let alerts = UIAlertController(title: "Hi", message: "Hello", preferredStyle: UIAlertControllerStyle.alert)
let action1 = UIAlertAction(title: "Yes", style: UIAlertActionStyle.default) { (<#UIAlertAction#>) in
for i in 0..<9
{
let newButton = self.view.viewWithTag(i) as! UIButton
newButton.setBackgroundImage(UIImage.init(named: ""), for: .normal)
}
}
#IBAction func buttonPressed(_ sender: UIButton)
{
sender.setBackgroundImage(UIImage.init(named: "cross.png"), for:.normal)
}
}
You need to add action to UIAlertController. Add following line after defining action1:
[alerts addAction: action1]
Try this:
first add button to the view and add action for it :
for i in 0..<9
{
let newButton = UIButton(frame : yourFrame)
newButton.setBackgroundImage(UIImage.init(named: ""), for: .normal)
newButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
newbutton.tag = i
self.view.addSubview(newButton:)
}
Try this :
newButton .setBackgroundImage(UIImage.init(named: ""), for: .normal)
newButton .setBackgroundImage(UIImage.init(named: "cross.png"), for: .selected)
#IBAction func buttonPressed(_ sender: UIButton)
{
sender.isSelected = !sender.isSelected;
}