iOS Swift Like Button in UITableView 's Cell - ios

I have a tableView in my app. and in my app users can like a post (best example is instagram). when I like a post my button state change to active and button's color change. but when I scroll the tableView button state back to normal. I know it happen because cell reload again, but what is the best solution for this problem? am I have to overtime that I press like button app send like request and tableview reloadData? (this is not good for server)
EDIT: I have a flag for button, but when I press like button I have to send request and fetch dataArray again. but how can change button state and send like request but not fetch dataArray. it will happen when user manually refresh data.
thanks.

You can set using if and else condition. see below example
if model.data.isFav == true
{
btnFav.selected = true
}
else
{
btnFav.selected = false
}

If you have any flag for button with Posts in your dataArray from which you are loading cells data then you can use that flag to set the color of button. It will take care at the time of scroll.

Set button type to custom in the navigation inspector, then set the background image for default and selected. then use the code below:
// MARK: Set fav button Action
func setFavButtonAction(_ sender : UIButton) {
print(sender.tag)
if sender.isSelected == true {
sender.isSelected = false
}else{
sender.isSelected = true
}
}

Related

How to hide table cell after choosing a drop down in swift 5?

I have a problem here..
So, I am using cocoapods for dropdown and table view controller,
and I want to hide the next cell if the dropdown says "Yes", and keep the next cell
when I hit " No ".
How do I do that?
How do I hide the next section?
Here my code & visual image.
Any help will be appreciated.
Thankyou
#IBAction func btnTapped(_ sender: Any) {
DropDown.show()
let choosen = DropDown.indexForSelectedRow
if choosen == 0 {
self.section2.isHidden = true
}
else if choosen == 1 {
self.section2.isHidden = false
}
}
Your dropdown function in getting called on button tap. You should use the delegate method of your dropdown function to know once user has chosen a value. Then inside that function you can hide unhide your cells.

Swift Radio Buttons - CheckBoxes - Swift 3

I work on Swift 3, and I'm trying to make checkboxes that behave like radio buttons. I explain myself : I have 8 buttons ; each has an "unchecked" image and a "checked" image. I want only 1 button to be selected (so, showing ITS "checked" image) at the time. The principle of radio buttons.
So I tried using the #IBAction with each button, I've this :
#IBAction func tona1_changed(_ sender: Any) {
if test_tona1.isSelected == true
{
test_tona1.setBackgroundImage(UIImage(named: "0b_unchecked"), for: UIControlState.normal)
test_tona1.isSelected = false
}
else
{
test_tona1.setBackgroundImage(UIImage(named: "0b_checked"), for: UIControlState.normal)
test_tona1.isSelected = true
}}
It actually make the image switch between "uncheck" and "check" but I don't know at all how to make it interact with the other buttons.
I tried using an array with the buttons's tags inside but I didn't have something working. I also tried to make a class but I don't know how it can work.
Thanks!
You can achieve that in several ways. One of the most trivial would be to:
Have a datasource. Most of the time an array.
Create an UIButton for each item in your datasource, and insert each button into another array. Each button would have a tag corresponding at the
index of the array. Also set different images for selected state and normal.
Add an action for each button, with the target function being something like:
func buttonPressed(sender:UIButton) {
for button in buttons {
button.isSelected = false
// deselect your model datasource[button.tag]
}
sender.isSelected = true
// select your model datasource[button.tag]
}
I leave the abstraction / improvements / safety to you. The key point is just to use a collection of buttons, iterate through them, and select / deselect them accordingly, and not using a big if/else checking for the button tag everytime.

Touch Up Inside not working properly

I have an app with some buttons, when those buttons are pressed the image on them should change. I assume that the TouchUpInside runs when you tap and remove the finger while still holding inside the area of the element, however it only works rarely and I'm not sure why.
The reason I use TouchUpInside instead of TouchDown is because I want the user to be able to cancel the action.
I'm sorry if I've misunderstood anything about those events and if this has already been asked. I couldn't find an answer to my problem searching the web.
//The IBAction is set to trigger on TouchUpInside
#IBAction func action11(sender: UIButton) {
setTile(sender)
}
func setTile(sender: UIButton) {
if turn {
print("O's turn")
sender.setImage(xTile, forState: .Normal)
turn = false
}
}
EDIT: Added the necessary code
There are some properties of UIButtons which you can use to achieve what you want.
You can use Default and selected state of uibutton to set two different images.
In XIB select state "Default" and assign default image to that state again select state to "Selected" and assign image which you want after button section.
and add following line in button selection method.
-(IBAction)buttonTapped:(UIButton *)sender{
sender.selected = !sender.selected;
}
Your understanding is correct, you need to use touchUpInside.
I assume you are trying to create a button that has a toggle function. On one touch you want the button to have the value Say "X" and when touched again the button has a value "O".
Take a look at this code below, this should do the job.
class ViewController: UIViewController {
var isButtonPressed = false{
// Adding a Property Observer, that reacts to changes in button state
didSet{
if isButtonPressed{
// Set the Value to X.
}else{
// Set the Value to O.
}
}
}
#IBAction func changeButtonValue(sender: UIButton) {
// Toggle the button value.
isButtonPressed = !isButtonPressed
}
}
If you don't set turn=true after the first time, this code is executed it will be executed only one.
if turn {
print("O's turn")
sender.setImage(xTile, forState: .Normal)
turn = false
}
Check if the button frame is large enough to get finger touch.
Apple says at least 35x35 pixel.

What's the simplest way to receive tap events on a disabled UIButton?

I have a UIButton on a form, and want to put it in a disabled state when the form is incomplete. However, I still want to be able to detect if a user attempts to press the button even in its disabled state so that the interface can let the user know that certain required fields on the form are not filled-in yet (and perhaps scroll to that field and point it out, etc.).
There doesn't seem to be any straightforward way to do this. I tried simply attaching a UITapGestureRecognizer to the UIButton but it doesn't respond when the button is in a disabled state.
I'd like to avoid subclassing UIButton if possible, unless it's the only way.
Create a fallback button. Put it behind the main button. Set its background and text colors to [UIColor clearColor] to ensure it won't show up. (You can't just set its alpha to 0 because that makes it ignore touches.) In Interface Builder, the fallback button should be above the main button in the list of subviews, like this:
Give it the same frame as the main button. If you're using autolayout, select both the main and fallback buttons and create constraints to keep all four edges equal.
When the main button is disabled, touches will pass through to the fallback button. When the main button is enabled, it will catch all the touches and the fallback button won't receive any.
Connect the fallback button to an action so you can detect when it's tapped.
Based on #rob idea, I sub-class a UIButton, and add a transparent button before someone addSubview on this button.
This custom UIButton will save many time about adjusting the UI components on the storyboard.
Update 2018/08
It works well, and add some enhanced detail to this sub-class. I have used it for 2 years.
class TTButton : UIButton {
// MARK: -
private lazy var fakeButton : UIButton! = self.initFakeButton()
private func initFakeButton() -> UIButton {
let btn = UIButton(frame: self.frame)
btn.backgroundColor = UIColor.clearColor()
btn.addTarget(self, action: #selector(self.handleDisabledTouchEvent), forControlEvents: UIControlEvents.TouchUpInside)
return btn
}
// Respect this property for `fakeButton` and `self` buttons
override var isUserInteractionEnabled: Bool {
didSet {
self.fakeButton.isUserInteractionEnabled = isUserInteractionEnabled
}
}
override func layoutSubviews() {
super.layoutSubviews()
// NOTE: `fakeButton` and `self` has the same `superView`.
self.fakeButton.frame = self.frame
}
override func willMoveToSuperview(newSuperview: UIView?) {
//1. newSuperView add `fakeButton` first.
if (newSuperview != nil) {
newSuperview!.addSubview(self.fakeButton)
} else {
self.fakeButton.removeFromSuperview()
}
//2. Then, newSuperView add `self` second.
super.willMoveToSuperview(newSuperview)
}
#objc private func handleDisabledTouchEvent() {
//NSLog("handle disabled touch event. Enabled: \(self.enabled)")
self.sendActionsForControlEvents(.TouchUpInside)
}
}
You have a great misunderstanding of user experience.
If a button is disabled, it is meant to be non-interactable.
You can not click on a disabled button, that is why it is disabled.
If you want to warn users about something when that button is clicked (e.g. form not filled correctly or completely), you need to make that button enabled. And just warn users when they click on it, instead of proceeding further with app logic.
Or you can keep that button disabled until form criteria are met, but show what is wrong with the form using another way, like putting exclamation marks near text fields, changing text field colors to red, or something like that...
But never try to add gesture recognizers, or hidden fallback buttons to a disabled button.
Check those and let me know if you see a disabled button:
https://airbnb.com/signup_login
https://spotify.com/us/signup/
https://netflix.com/signup/regform
https://reddit.com/register/
https://twitter.com/signup
https://facebook.com/r.php
https://appleid.apple.com/account
https://accounts.google.com/SignUp
https://login.yahoo.com/account/create
https://signup.live.com/signup
All the proceed buttons on these websites are always enabled, and you get feedback about what is wrong when you try to continue.
And here is really good answer: https://ux.stackexchange.com/a/76306
Long story short: disabled UI elements meant to be not-interactable.
Trying to make them interactable while they are disabled is the same to making them enabled in the first place.
So, for your question's case, it is just a styling issue. Just try styling your button, instead of making it disabled/enabled.

Disable user interaction on tabBar

I am displaying an image right after the app didFinishLaunchingWithOptions, the app consists in a tab bar, and in the first view i have some buttons.
The user can only continue to use the app after he press the button in that first image, the problem is, some users can interact with the tab bar, and the buttons in the first view even with the image above all.
How i can completely disable the user interaction on those buttons and in the tabBar, and enable then only when the button is pressed and the image disapear?
To disable:
UITabBarController.tabBar.userInteractionEnabled = NO;
To enable:
UITabBarController.tabBar.userInteractionEnabled = YES;
if let items = self.tabBarController?.tabBar.items {
for i in 0 ..< items.count {
let itemToDisable = items[i]
itemToDisable.isEnabled = false
}
}
somehow i didn't fully understand what you described,but have you tried disabling your buttons using following code?
button1.Enabled=false;
also you can disable images click function using
image1.Enabled=false;

Resources