Calling a UIButton action from a UITableViewCell - ios

I dynamically created several buttons in my UITableviewCell class like so:
for (clientObjectId, _) in connectedObjectIds {
self.clientNameButton = UIButton(type: UIButtonType.System) as UIButton
self.clientNameButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail
self.clientNameButton.frame = CGRectMake(self.leftSideSpaceForUsersAndUserLabel, clientNameButtonFrameHeight, self.nameButtonWidth, self.nameButtonHeight)
self.clientNameButton.setTitle(self.userObjectIdsAndNames[clientObjectId], forState: UIControlState.Normal)
self.clientNameButton.titleLabel!.font = UIFont(name: "Helvetica", size: 12.0)
self.clientNameButton.addTarget(self, action: "asdf:", forControlEvents: UIControlEvents.TouchUpInside)
self.nameButtons.append(self.clientNameButton)
self.addSubview(self.clientNameButton)
}
However, I can't seem to find a way to call the following function in my table view cell class:
func asdf(sender:UIButton) {
print("Button tapped")
}
I don't really care so much about being able to call it in my UITableViewCell class as much as my calling the function in my table view class.
Anybody have a solution to this problem?

for (clientObjectId, _) in connectedObjectIds {
self.clientNameButton = UIButton(type: UIButtonType.System) as UIButton
self.clientNameButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail
self.clientNameButton.frame = CGRectMake(self.leftSideSpaceForUsersAndUserLabel, clientNameButtonFrameHeight, self.nameButtonWidth, self.nameButtonHeight)
self.clientNameButton.setTitle(self.userObjectIdsAndNames[clientObjectId], forState: UIControlState.Normal)
self.clientNameButton.titleLabel!.font = UIFont(name: "Helvetica", size: 12.0)
self.clientNameButton.addTarget(self, action: "asdf:", forControlEvents: UIControlEvents.TouchUpInside)
self.nameButtons.append(self.clientNameButton)
self.addSubview(self.clientNameButton)
}

Related

How can I add a target to my button in an extension?

I wrote an extension to display an empty state if my view controller is empty. I also wanted to add a UIButton() with a target. How can I implement the addTarget action for my button within the extension? (F.e. a simple "Hello World" or what ever I need)
extension UITableView{
func setEmptyView(title: String, message: String) {
// handling states
button.setTitle("+ Add New Documentation", for: .normal)
button.titleLabel!.font = UIFont(name: "Roboto-Regular", size: 24)
button.setTitleColor(UIColor(hex: "BDC86F"), for: .normal)
button.backgroundColor = UIColor(hex: "506182")
button.addTarget...
//more code
emptyView.addSubview(button)
}
}
I have achieved the same thing for UIView extension. Hope, It will help you and I assume that you're able to convert it for UITableView
Code:
extension UIView{
func setEmptyView(title: String, message: String) {
let emptyView = UIView(frame: self.bounds)
// handling states
let button = UIButton(frame: emptyView.bounds)
button.setTitle("+ Add New Documentation", for: .normal)
button.titleLabel!.font = UIFont(name: "Roboto-Regular", size: 24)
button.setTitleColor(UIColor.red, for: .normal)
button.backgroundColor = UIColor.black
button.addTarget(self, action: #selector(btnTapEvent(sender:)), for: .touchUpInside)
emptyView.addSubview(button)
//more code
self.addSubview(emptyView)
}
#objc func btnTapEvent(sender:UIButton){
print("btnTapEvent")
}
}
Reference image:

Change Color of Programmatically Created Button when Pressed

I'm using a function to create multiple buttons for my game.
func createButton() {
let button = UIButton()
button.setTitle("", for: .normal)
button.frame = CGRect(x:15, y: 50, width: 200, height:100)
button.backgroundColor = UIColor.red
self.view.addSubview(button)
button.addTarget(self, action: Selector(("buttonPressed:")), for:
.touchUpInside)
}
I call this function once for testing in viewDidLoad function, but I don't know what code I should put into my buttonPressed() function for the color of my button to change? I tried doing
self.backgroundColor = UIColor.blue
but that didn't work. I also tried using UIButton and button instead of self, but both of those didn't work either. What should I do?
Your code isn't clean Swift 4 code. Here's how to do this:
Create your button like you are, but change Selector to #selector:
func createButton() {
let button = UIButton()
button.setTitle("", for: .normal)
button.frame = CGRect(x:15, y: 50, width: 200, height:100)
button.backgroundColor = UIColor.red
self.view.addSubview(button)
button.addTarget(self, action: #selector((buttonPressed)), for: .touchUpInside)
}
Use the sender that is automatically added:
#objc func buttonPressed(sender: UIButton) {
sender.backgroundColor = UIColor.blue
}
Additionally may I offer a few suggestions?
Check the background color before changing it. No sense in needlessly changing a button that is already blue.
Since you aren't setting the title to your button, set the tag property (you can even add this as a parameter to createButton). This way you can know which button was tapped.
Just make the button an instance property.
let changingButton = UIButton()
func createButton() {
changingButton.backgroundColor = UIColor.red
changingButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
}
#objc func buttonPressed() {
changingButton.backgroundColor = UIColor.blue
}

UIButton Function add Tap Style

I Have written a function in Swift 4 which creates a button that receives the UIButton, a Color and a String for the title. I would like to add to this function a highlight or tap style but I am not sure how.
The function:
func homeBtn(button: UIButton, color: UIColor, title: String){
button.setTitle(title, for: .normal)
button.setTitleColor(color, for: .normal)
button.titleLabel?.font = UIFont(name: "Raleway-Medium", size: 24)
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.titleEdgeInsets = UIEdgeInsetsMake(20,20,20,20)
button.layer.borderColor = color.cgColor
button.layer.borderWidth = 2
button.layer.cornerRadius = button.frame.width/2
button.layer.backgroundColor = whiteColor.cgColor
}
The button is a circle and has a String centered in the middle with the UIColor being used as an outline. Can someone show me how to add a tap style to this function that uses the same UIColor to fill in the button and turn the text white please?
For the title color you can easily do this without adding events.
button.setTitleColor(.white, for: .highlighted)
button.setTitleColor(.black, for: .normal)
For the background color you need to define the following events:
button.addTarget(self, action: #selector(touchDown(button:)), for: .touchDown)
button.addTarget(self, action: #selector(touchUpInside(button:)), for: .touchUpInside)
Define functions - You can refer additional touch types as well - see UIControlEvents
#objc func touchDown(button: UIButton) {
guard let borderColor = button.layer.borderColor else {
return
}
button.backgroundColor = UIColor(cgColor: borderColor)
}
#objc func touchUpInside(button: UIButton) {
// Set backgroundColor for normal state...
}

Swift button created programmatically needs to have 2 lines for title

I am creating buttons programmatically like this:
let stage: Stages = stagesObjectsArray[i]
let button = UIButton(type: .Custom) as UIButton
button.setTitle(stage.name, forState: .Normal)
button.sizeToFit()
button.frame.origin = buttonPosition
let buttonIncrement = button.frame.size.width + padding.width
buttonPosition.x = buttonPosition.x + buttonIncrement
button.backgroundColor = UIColor.blackColor()
button.titleLabel?.font = UIFont(name: "", size: widthOfScreen/3.2)
button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
button.tag = stage.id
button.addTarget(self, action: #selector(GamesAllViewController.buttonPressedTopMenu(_:)), forControlEvents: .TouchUpInside)
buttonView.addSubview(button)
What I want to implement and can't figure out how is to have the title of the button on 2 rows if the width of the button becomes too big(for instance more than half the width of the screen).
I have found some questions on this topic, but they all assume they know the title of the button, while in my case it is dynamic and I do not know what it might be.
I have tried this code, but with no change:
button.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel!.numberOfLines = 2
Can somebody help?
You can use "\n" and NoOFLines to 0
try this code
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
let button = UIButton(type: .Custom) as UIButton
button.setTitle("Line 1\nLine 2", forState: .Normal)
button.sizeToFit()
button.titleLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel!.numberOfLines = 0
button.titleLabel!.textAlignment = NSTextAlignment.Center
button.frame = CGRectMake(20, 100, 280, 40)
button.titleLabel?.textColor = UIColor.redColor()
button.backgroundColor = UIColor.blackColor()
button.addTarget(self, action: "methodName:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}

How to change element title inside UITableViewCell?

I have a button on custom tableviewcell. I've been able add action to this button by add target like below code:
var playButton = cell.contentView.viewWithTag(5) as? UIButton
var sender : UIButton = UIButton()
playButton?.addTarget(self, action: "playPost:", forControlEvents: UIControlEvents.TouchUpInside)
playButton?.layer.setValue(object["previewUrl"] as? String, forKey: "songUrl")
playButton?.layer.setValue(indexPath.row, forKey: "index")
But, how can I change it's title whenever I clicked this button?
If your function is playPost(), you could change the value passed in (which is the sender of the function, by default) like this:
func playPost(sender: UIButton) {
sender.setTitle("New title", forState: UIControlState.Normal);
}
You can Change UIButton title by using setTitle Method
Example
var button = UIButton(frame: CGRect(x: 50, y: 50, width: 200, height: 100))
button.backgroundColor = UIColor.blackColor()
button.setTitle("Start", forState: UIControlState.Normal)
button.addTarget(self, action: "pressButton:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
func pressButton(sender:UIButton)
{
if sender.titleLabel?.text == "Start"
{
sender.setTitle("Stop", forState: UIControlState.Normal)
}
else
{
sender.setTitle("Start", forState: UIControlState.Normal)
}
}

Resources