sender button changes when i click play button but when i click another button in the tableview the button first button image not changes to play
#IBAction func playSound(sender: UIButton) {
if self.player != nil && self.player.playing {
player.stop()
sender.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
}
else {
sender.setImage(UIImage(named: "pause.png"), forState: UIControlState.Normal)
}
}
**Try this code ...**
Declare one variable for get index.
var songnamearray : NSArray = NSArray()
var audioPlayer = AVAudioPlayer()
var selectedindex : Int?
var isFristtime : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
songnamearray = ["Saiyaan (Sanam) 320Kbps(MajMasti.in)" ,"Phone Mein Teri Photo (Neha Kakkar) - 320 Kbps(GoldMusic.In)" ,"Mile Ho Tum Humko (Neha Kakkar) - 320 Kbps(GoldMusic.In)" ," Rain Mashup (Neha Kakkar) - 320 Kbps(GoldMusic.In)" ,"Car Mein Music Baja (Neha Kakkar) 320Kbps"]
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songnamearray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Songcell", forIndexPath: indexPath)
// info 5 play 6 name 7
let eventname: UILabel = (cell.viewWithTag(7) as! UILabel)
let info: UIButton = (cell.viewWithTag(5) as! UIButton)
let play: UIButton = (cell.viewWithTag(6) as! UIButton)
if selectedindex == indexPath.row{
if isFristtime == true
{
play.setImage(UIImage(named: "pause-button.png"), forState: UIControlState.Normal)
}else{
play.setImage(UIImage(named: "play-button.png"), forState: UIControlState.Normal)
}
}else{
play.setImage(UIImage(named: "play-button.png"), forState: UIControlState.Normal)
}
info.setImage(UIImage(named: "icon (5).png"), forState: UIControlState.Normal)
play.addTarget(self, action: #selector(self.CloseMethod(_:event:)), forControlEvents: .TouchDown)
info.addTarget(self, action: #selector(self.CloseMethod1(_:event:)), forControlEvents: .TouchDown)
eventname.text = songnamearray.objectAtIndex(indexPath.row) as? String
return cell
}
#IBAction func CloseMethod(sender: UIButton, event: AnyObject) {
let touches = event.allTouches()!
let touch = touches.first!
let currentTouchPosition = touch.locationInView(self.Songlisttable)
let indexPath = self.Songlisttable.indexPathForRowAtPoint(currentTouchPosition)!
selectedindex = indexPath.row
if isFristtime == true
{
audioPlayer.pause()
isFristtime = false
}else{
let songnamestring : NSString = songnamearray.objectAtIndex(indexPath.row) as! String
do {
if let bundle = NSBundle.mainBundle().pathForResource(songnamestring as String, ofType: "mp3") {
let alertSound = NSURL(fileURLWithPath: bundle)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
} catch {
print(error)
}
isFristtime = true
}
self.Songlisttable.reloadData()
}
Try to set background image for button
let image = UIImage(named: "play.png") as UIImage
sender.setBackgroundImage(image, forState: UIControlState.Normal)
Hope this helps.
It is that call radio button. I never use radio button in cell. It is hard for me. I'm newbie. If U need it, it is that: Radio button logic in UItableViewCells.
But i use other way: didSelectRowAtIndexPath. When u click in cell, button current is show pause image, and other button is show play image. U can reference it
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
currentIndexPath = indexPath;
YourTableViewCell *cell = nil;
if (!previousIndexPath) {
previousIndexPath = currentIndexPath;
}
if (previousIndexPath != currentIndexPath) {
cell = (YourTableViewCell *) [_yourTableView cellForRowAtIndexPath:previousIndexPath];
[cell.radioBtn setBackgroundImage:[UIImage imageNamed:#"play"] forState:UIControlStateNormal];
cell = (YourTableViewCell *) [_yourTableView cellForRowAtIndexPath:currentIndexPath];
[cell.radioBtn setBackgroundImage:[UIImage imageNamed:#"pause"] forState:UIControlStateNormal];
previousIndexPath = currentIndexPath;
}
if (previousIndexPath == currentIndexPath) {
cell = (YourTableViewCell *) [_yourTableView cellForRowAtIndexPath:previousIndexPath];
[cell.radioBtn setBackgroundImage:[UIImage imageNamed:#"pause"] forState:UIControlStateNormal];
}
}
Related
I have a problem when I click a button in UITableView.
When I click a button to change its image, another indexpath changes it image.
Two buttons change their image when I click one button.
This video is shown the problem :
Video Shown Problem
This is my code to button click :
#objc func btnAction(_ sender: UIButton) {
let section = 0
let row = sender.tag
let indexPath = IndexPath(row: row, section: section)
//let point = sender.convert(CGPoint.zero, to: servicestable as UIView)
// let indexPath: IndexPath! = servicestable.indexPathForRow(at: point)
let cell: ServicesCell = self.servicestable.cellForRow(at: indexPath) as! ServicesCell
print(sender.tag)
if services[indexPath.row].choose == "0" {
cell.check.setImage(UIImage(named: "Rectangle1"), for: .normal)
services[indexPath.row].choose = "1"
// checkchoose.updateValue(1, forKey: indexPath.row)
print("number: " + String(indexPath.row))
chooseservicesw.updateValue("0", forKey: String(indexPath.row+1))
// servicestable.reloadData()
}
else if services[indexPath.row].choose == "1" {
cell.check.setImage(UIImage(named: "checkbox1"), for: .normal)
services[indexPath.row].choose = "0"
// checkchoose.updateValue(0, forKey: indexPath.row)
print("number: " + String(indexPath.row))
chooseservicesw.removeValue(forKey: String(indexPath.row+1))
// servicestable.reloadData()
} }
and this is my code to Cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:ServicesCell = servicestable.dequeueReusableCell(withIdentifier: "servicess", for: indexPath) as! ServicesCell
cell.name.text = services[indexPath.row].name
let photo = services[indexPath.row].icon
let imgURL = MainUrl + photo! // or jpg
// cell.icon.setImageFromURl(stringImageUrl: imgURL)
let url = URL(string: imgURL)
cell.icon.kf.setImage(with: url)
// print(checkchoose[indexPath.row])
print(services[indexPath.row].choose)
cell.check.tag = indexPath.row
cell.check.addTarget(self, action: #selector(self.btnAction(_:)), for: .touchUpInside)
cell.checkpay.tag = indexPath.row
cell.checkpay.addTarget(self, action: #selector(self.btnAction2(_:)), for: .touchUpInside)
cell.price.addTarget(self, action: #selector(self.endedit(_:)), for: .editingDidEnd)
cell.price.addTarget(self, action: #selector(self.endedit(_:)), for: .editingChanged)
cell.selectionStyle = .none
return cell
}
When you perform dequeueReusableCell, iOS not generates your array's counts of cells. Instead of this, it generates fewer cells and use these cells again and again on scrolls. In your case selected shown cells are actually same cells.
The solution: You should store the selection flag for your cells in your datasource array (in your case its services). And in cellForRowAt method you should select or deselect checkboxes according to your stored selection data.
Edit:
if services[indexPath.row].choose == "0" {
cell.check.setImage(UIImage(named: "Rectangle1"), for: .normal)
services[indexPath.row].choose = "1"
chooseservicesw.updateValue("0", forKey: String(indexPath.row+1))
} else if services[indexPath.row].choose == "1" {
cell.check.setImage(UIImage(named: "checkbox1"), for: .normal)
services[indexPath.row].choose = "0"
chooseservicesw.removeValue(forKey: String(indexPath.row+1))
}
Add this part to end of your cellForRowAt method.
This problem is because reuseable cell in Memory you can handle like that:
In Your ViewController or TableViewController add Array that handel selected Model selectedIndexPathServices Add your YourServiceModel
Example
class TableViewController: UITableViewController {
var selectedIndexPathServices :[YourServiceModel] = [YourServiceModel]()
override func viewDidLoad() {
super.viewDidLoad()
}
}
At your btnAction
#objc func btnAction(_ sender: UIButton) {
guard let cell = sender.superview?.superview as? ServicesCell else { return}
let indexPath = self.tableView.indexPath(for: cell)
if selectedIndexPathServices.contains(services[indexPath.row]){
selectedIndexPathServices.remove(at: indexPath.row)
}else{
selectedIndexPathServices.append(services[indexPath.row])
}
}
At your cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:ServicesCell = servicestable.dequeueReusableCell(withIdentifier: "servicess", for: indexPath) as! ServicesCell
cell.name.text = services[indexPath.row].name
let photo = services[indexPath.row].icon
let imgURL = MainUrl + photo! // or jpg
// cell.icon.setImageFromURl(stringImageUrl: imgURL)
let url = URL(string: imgURL)
cell.icon.kf.setImage(with: url)
// print(checkchoose[indexPath.row])
if selectedIndexPathServices.contains(services[indexPath.row]){
if services[indexPath.row].choose == "0" {
cell.check.setImage(UIImage(named: "Rectangle1"), for: .normal)
services[indexPath.row].choose = "1"
chooseservicesw.updateValue("0", forKey: String(indexPath.row+1))
}
else if services[indexPath.row].choose == "1" {
cell.check.setImage(UIImage(named: "checkbox1"), for: .normal)
services[indexPath.row].choose = "0"
chooseservicesw.removeValue(forKey: String(indexPath.row+1))
}
}
cell.check.tag = indexPath.row
cell.check.addTarget(self, action: #selector(self.btnAction(_:)), for: .touchUpInside)
cell.checkpay.tag = indexPath.row
cell.checkpay.addTarget(self, action: #selector(self.btnAction2(_:)), for: .touchUpInside)
cell.price.addTarget(self, action: #selector(self.endedit(_:)), for: .editingDidEnd)
cell.price.addTarget(self, action: #selector(self.endedit(_:)), for: .editingChanged)
cell.selectionStyle = .none
return cell
}
I have one UITableViewCell. In TableViewCell, I have 7 buttons in single row. I want to play music. When i press button1, its background colour should be changed. If I pressed button2, its background colour should be changed, and button1 would be deselect. I also set the tag for each button in row, but i don't understand, how to do? Sound is playing fine but i am unable to select and deselect buttons. I am using swift3. Thanks in advance.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> tableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell") as! tableViewCell
cell.Btn_one.addTarget(self, action: #selector(TableViewController.BtnAction_One), for: .touchUpInside)
//For example
if (cell.Btn_one.tag == 1){
cell.Btn_one.backgroundColor = .white
}else if (cell.Btn_two.tag == 2){
cell.Btn_two.backgroundColor = .red
}
}
#IBAction func BtnAction_One(_ sender: UIButton) {
self.play()
}
#Chetan solution for this : first one
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellData", for: indexPath)
let btn1 = cell.viewWithTag(1) as! UIButton
let btn2 = cell.viewWithTag(2) as! UIButton
let btn3 = cell.viewWithTag(3) as! UIButton
let btn4 = cell.viewWithTag(4) as! UIButton
let btn5 = cell.viewWithTag(5) as! UIButton
let btn6 = cell.viewWithTag(6) as! UIButton
btn1.addTarget(self, action: #selector(btnClicked(sender:)), for: .touchUpInside)
btn2.addTarget(self, action: #selector(btnClicked(sender:)), for: .touchUpInside)
btn3.addTarget(self, action: #selector(btnClicked(sender:)), for: .touchUpInside)
btn4.addTarget(self, action: #selector(btnClicked(sender:)), for: .touchUpInside)
btn5.addTarget(self, action: #selector(btnClicked(sender:)), for: .touchUpInside)
btn6.addTarget(self, action: #selector(btnClicked(sender:)), for: .touchUpInside)
return cell
}
when this will to btnClicked
` func btnClickec(sender:UIButton){
sender.isSelected = true
let cell = sender.superview?.superview as! UITableViewCell
let btn1 = cell.viewWithTag(1) as! UIButton
let btn2 = cell.viewWithTag(2) as! UIButton
let btn3 = cell.viewWithTag(3) as! UIButton
let btn4 = cell.viewWithTag(4) as! UIButton
let btn5 = cell.viewWithTag(5) as! UIButton
let btn6 = cell.viewWithTag(6) as! UIButton
let arr = [btn1,btn2,btn3,btn4,btn5,btn6];
for index in 0...5{
let btn = arr[index]
if index+1 == sender.tag{
btn.isSelected = true
}else{
btn.isSelected = false
}
}
}
`
And second one : or you can collection view inside tableviewcell also
This is how I did it:
first the function:
func switchColor(isWhite: Bool, sender: UIButton) {
if isWhite == true {
sender.backgroundColor = UIColor.clear
sender.setTitleColor(UIColor.white, for: UIControlState.normal)
}else if isWhite == false {
sender.backgroundColor = UIColor.white
sender.setTitleColor(UIColor.clear, for: UIControlState.normal)
}
Then where I call it:
#IBAction func RepeatWeeklyPressed(_ sender: UIButton) {
if sender.backgroundColor == UIColor.white {
switchColor(isWhite: true, sender: sender)
}else {
switchColor(isWhite: false, sender: sender)
}
print("Pressed a repeat button")
}
Hope this helps!
Well, I suggest you to subclass from UIButton, like this:
class CustomButton: UIButton {
var isPressed = false
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(frame: CGRect, title: String, tag: Int) {
self.init(frame: frame)
self.frame = frame
setTitle(title, for: .normal)
setTitleColor(.white, for: .normal)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
switch tag {
case 0: //Play a music
if isPressed{
backgroundColor = .black
} else {
backgroundColor = .clear
}
case 1: //Play a video
if isPressed{
backgroundColor = .black
} else {
backgroundColor = .clear
}
default: //Other
if isPressed{
backgroundColor = .black
} else {
backgroundColor = .clear
}
}
if isPressed { isPressed = false } else { isPressed = true }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
After that, in your cell I'd have some like...
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: nil)
let musicB = CustomButton(frame: CGRect(x: 0, y: 0, width: 0, height: 0), title: "1", tag: 1)
addSubview(musicB)
}
You'll want to subclass the button as CustomButton or whatever you would like to call it. And you'll need to create a delegate to let your viewcontroller know whats up.
Create a func that takes in an integer. This will be the code that'll take in your button's tag and preform some code. #Gabs had the right idea there.
func select(index: Int) {
switch sender.tag {
case 0: //do something
case 1: //do something
}
}
Create a single IBAction then link all your buttons to it. Inside, call the method created above
#IBAction func buttonTapped(_ sender: Any) {
select(index: sender.tag)
}
all that's missing is the viewController being informed on which button has been tapped. Set a delegate for it in your CustomCell view file and have it capture the sender.tag in your IBAction. Be sure to conform your viewcontroller too so the delegation works.
I am making a quiz in a tableView that has 4 Buttons (options), I tagged them on a story board like 201,202,203,204 and got all of them successfully in tableView methods. But after adding targets to buttons, I am not able to get particular buttons in buttonClicked method.
func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return questions.count }
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
(cell.viewWithTag(100) as! UILabel).text = "Q : " + (questions[indexPath.row].objectForKey("MocQuestion")! as? String)!
(cell.viewWithTag(100) as! UILabel).font = themeFont
(cell.viewWithTag(101) as! UILabel).text = questions[indexPath.row].objectForKey("Op1")! as? String
(cell.viewWithTag(102) as! UILabel).text = questions[indexPath.row].objectForKey("Op2")! as? String
(cell.viewWithTag(103) as! UILabel).text = questions[indexPath.row].objectForKey("Op3")! as? String
(cell.viewWithTag(104) as! UILabel).text = questions[indexPath.row].objectForKey("Op4")! as? String
let btn1 = (cell.viewWithTag(201) as! UIButton)
let btn2 = (cell.viewWithTag(202) as! UIButton)
let btn3 = (cell.viewWithTag(203) as! UIButton)
let btn4 = (cell.viewWithTag(204) as! UIButton)
// btn1.tag = indexPath.row * 100 + 0
// btn1.tag = indexPath.row * 100 + 1
// btn1.tag = indexPath.row * 100 + 2
// btn1.tag = indexPath.row * 100 + 3
btn1.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
btn2.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
btn3.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
btn4.addTarget(self, action: #selector(Quiz.buttonClicked(_:)),forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func buttonClicked(sender:UIButton)
{
let tag = sender.tag
print(tag)
}
If you want the indexPath to access the questions Array then you can try like this.
func buttonClicked(sender:UIButton) {
let center = sender.center
let point = sender.superview!.convertPoint(center, toView:self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(point)
//Now you have tag of button check for that
if (sender.tag == 201) {
print("Option A")
}
else if (sender.tag == 202) {
print("Option B")
}
else if (sender.tag == 203) {
print("Option C")
}
else {
print("Option D")
}
print(question[indexPath.row])
}
In swift 3 You can try bellow like
My table cell class
class Custom_Cell: UITableViewCell {
#IBOutlet weak var ButtonA: UIButton!
#IBOutlet weak var ButtonB: UIButton!
#IBOutlet weak var ButtonC: UIButton!
}
Set Tag in table view
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Custom_Cell;
cell.ButtonA.tag = indexPath.row;
cell.ButtonB.tag = indexPath.row;
cell.ButtonA.tag = indexPath.row;
//Add Action Methods to UIButtons
cell.ButtonA.addTarget(self, action: #selector(ButtonAAction), for: .touchUpInside)
cell.ButtonB.addTarget(self, action: #selector(ButtonBAction), for: .touchUpInside)
cell.ButtonA.addTarget(self, action: #selector(ButtonCAction), for: .touchUpInside)
return cell;
}
Button Action will look like ..
func ButtonAAction(_ sender: Any) {
//Get Button cell position.
let ButtonPosition = (sender as AnyObject).convert(CGPoint.zero, to: tableView)
let indexPath = tableView.indexPathForRow(at: ButtonPosition)
if indexPath != nil {
print("Cell indexPath: \(indexPath?.row)")
}
}
In order to get every ques separate button click event you can pass the unique ID as postfix or prefix e.g 20101 or 01201 of every ques as a tag of button instead of hard-coded. Then get the tag and extract ques id first now proceed for examination as per ques.
I'm adding UIButton in UITableView, I'm trying to change UIButton background color, UIButton title color and UIButton image color on table view cell selection and same vice versa.
MY Code is
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let propertyCell = tablePropertyList.cellForRowAtIndexPath(indexPath) as! PropertyListTableCell
propertyCell.buttonDownload.selected = true
propertyCell.buttonDownload.setTitleColor(utility!.uicolorFromHex(0xf8f8f8), forState: UIControlState.Selected)
let image:UIImage = UIImage(named: "DownloadSelected")!
propertyCell.buttonDownload.setImage(image, forState: UIControlState.Selected)
propertyCell.buttonDownload.backgroundColor = utility!.uicolorFromHex(0x006747)
propertyCell.buttonDownload.layer.borderColor = utility!.uicolorFromHex(0x006747).CGColor
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath)
{
let propertyCell = tablePropertyList.cellForRowAtIndexPath(indexPath) as! PropertyListTableCell
propertyCell.buttonDownload.selected = false
propertyCell.buttonDownload.setTitleColor(utility!.uicolorFromHex(0x006747), forState: UIControlState.Normal)
let image:UIImage = UIImage(named: "Download")!
propertyCell.buttonDownload.setImage(image, forState: UIControlState.Normal)
propertyCell.buttonDownload.backgroundColor = utility!.uicolorFromHex(0xf8f8f8)
propertyCell.buttonDownload.layer.borderColor = utility!.uicolorFromHex(0xf8f8f8).CGColor
}
//on UIButton Action
MY Code is
func downloadViewAction(sender: UIButton)
{
sender.selected = true
sender.setTitleColor(utility!.uicolorFromHex(0xf8f8f8), forState: UIControlState.Selected)
let image:UIImage = UIImage(named: "DownloadSelected")!
sender.setImage(image, forState: UIControlState.Selected)
sender.backgroundColor = utility!.uicolorFromHex(0x006747)
sender.layer.borderColor = utility!.uicolorFromHex(0x006747).CGColor
print("inside ownload action view")
let splitView:UISplitViewController = DevelopmemtSplitViewController()
if let path = tablePropertyList.indexPathForSelectedRow {
let selectedproperty = propertyArray[path.row]
self.showActivityIndicator(splitView.view, message: "Downloading properties for "+selectedproperty)
}
}
awakeFromNib method of cell class can be used to change titlecolor, image of button based on state. Please refer following code
class PropertyListTableCell : UITableViewCell
{
func awakeFromNib()
{
propertyCell.buttonDownload.setTitleColor(utility!.uicolorFromHex(0x006747), forState: UIControlState.Normal)
propertyCell.buttonDownload.setTitleColor(utility!.uicolorFromHex(0xf8f8f8), forState: UIControlState.Selected)
}
}
func downloadViewAction(sender: UIButton)
{
sender.selected = true //automatically changes titlecolor of button
}
If I'm getting it right. You have a button inside every PropertyListTableCell and you want to change the way that button looks depending on the selection state of the cell.
If so, overwrite the setSelected(_:animated:) function in your PropertyListTableCell class, this way, whenever a cell is selected or deselect the button appearance will change automatically.
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: true);
if (selected) {
self.buttonDownload.backgroundColor = utility!.uicolorFromHex(0x006747)
self.buttonDownload.layer.borderColor = utility!.uicolorFromHex(0x006747).CGColor
}
else {
propertyCell.buttonDownload.backgroundColor = utility!.uicolorFromHex(0xf8f8f8)
propertyCell.buttonDownload.layer.borderColor = utility!.uicolorFromHex(0xf8f8f8).CGColor
}
self.buttonDownload.selected = true;
}
As commented Savitha above, the button image and the title color can be defined just once in the awakeFromNib (for example).
And there is no need to change any visual in the button action function because it's done when selecting the cell:
func downloadViewAction(sender: UIButton) {
let cell = sender as! as! PropertyListTableCell;
let indexPath = tableView.indexPathForCell(cell);
tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .None);
print("inside ownload action view")
let selectedproperty = propertyArray[path.row]
self.showActivityIndicator(splitView.view, message: "Downloading properties for "+selectedproperty)
}
I have a preset image of a button in a custom cell, and I want that image to change when the button is clicked. How would I do that? I put a switch in the button, and it works. When it is clicked it will play a song, and when it is clicked again it will stop. I just want the image to change. How would I do that? The name of the button is playbutton.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = friendstable.dequeueReusableCellWithIdentifier("friendcell", forIndexPath: indexPath) as! FriendsMusicCell
cell.playbutton.tag = indexPath.row
cell.playbutton.addTarget(self, action: "playmusic:", forControlEvents: .TouchUpInside)
cell.customtitle.text = titleofsong[indexPath.row]
cell.customartist.text = artist[indexPath.row]
cell.customtitle.font = UIFont(name: "Lombok", size: 22)
cell.customtitle.textColor = UIColorFromRGB("4A90E2")
cell.customartist.font = UIFont(name: "Lombok", size: 16)
cell.customartist.textColor = UIColor.blackColor()
cell.customtitle.numberOfLines = 0;
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.backgroundColor = UIColor.clearColor()
return cell
}
func playmusic(sender: UIButton!) {
let playButtonrow = sender.tag
print(titleofsong[playButtonrow])
switch(buttonState){
case 0:
let searchTerm: String = titleofsong[playButtonrow]
let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music"
let url: NSURL = NSURL(string: urlPath)!
print("Search iTunes API at URL \(url)")
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) -> Void in
do {
if let dict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
{
let previewUrl = NSURL(string: (dict["results"]![0]["previewUrl"] as? String)!)!
print(previewUrl)
self.player = AVPlayer(URL: previewUrl)
self.player.rate = 1.0
self.player.play()
}
} catch let jsonError as NSError {
}
}
task.resume()
}
buttonState = 1;
break;
case 1:
player.pause()
buttonState = 0;
default: break
}
}
You don't need to declare playButton globally
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = friendstable.dequeueReusableCellWithIdentifier("friendcell", forIndexPath: indexPath) as! FriendsMusicCell
cell.playbutton.tag = indexPath.row
cell.playButton.setImage(playImage, forState: UIControlState.Normal)
cell.playButton.setImage(pauseImage, forState: UIControlState.Selected)
cell.playbutton.addTarget(self, action: "playmusic:", forControlEvents: .TouchUpInside)
cell.customtitle.text = titleofsong[indexPath.row]
cell.customartist.text = artist[indexPath.row]
cell.customtitle.font = UIFont(name: "Lombok", size: 22)
cell.customtitle.textColor = UIColorFromRGB("4A90E2")
cell.customartist.font = UIFont(name: "Lombok", size: 16)
cell.customartist.textColor = UIColor.blackColor()
cell.customtitle.numberOfLines = 0;
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.backgroundColor = UIColor.clearColor()
return cell
}
in your playmusic function you can add the following line at the beginning
sender.selected = !sender.selected
It 's so easy. You can set image for uibutton with UIControlState
ex:
self.btnPlay.setImage(playImage, forState: UIControlState.Normal)
self.btnPlay.setImage(pauseImage, forState: UIControlState.Selected)
And When you click it, you change state of btnPlay:
self.btnPlay.selected = !self.btnPlay.selected