swift UIButton click unavailable out of tableview cell - swift

the following code, click event works.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "SwiftCell")
let button = UIButton()
button.setTitle(hiddenGear ? "+" : "-", for: .normal)
button.setTitleColor(UIColor.lightGray, for: .normal)
button.addTarget(self, action:#selector(self.toggleGear), for: .touchUpInside)
button.frame = CGRect(x: self.view.frame.width - 36, y: 0, width: 30, height: 30)
button.backgroundColor = UIColor.red
cell.addSubview(button)
but what i want just like below:
move UIButton out of the uitableview cell, and the click event does not work.
button.frame = CGRect(x: self.view.frame.width - 36, y: -30, width: 30, height: 30)
try to use cell.bringSubview(toFront: button) , but it does not work too. have any idea?

This is illegal:
cell.addSubview(button)
You may not add a view to the cell. You must add the view only to the cell's contentView.
But the content view does not extend all the way to the right. If you want the view all the way over at the right, you must provide it as an accessory view.
Finally, you cannot easily add a working button outside the cell bounds, because a subview outside its superview's bounds is not touchable. You can make it touchable, however, by munging the hit-testing for the superview. You would need to override this method:
https://developer.apple.com/documentation/uikit/uiview/1622469-hittest

You need to use constraints, relative to the top of that UITableViewCell. Also, I can see you are trying to create a '+' (plus) icon in the corner. Consider using a Navigation Item found in the Object Library.

First it's not preferred to add UI elements inside cellForRow because of reusing , second you can encapsulate the button inside the cell and play with the background color to fake that it's out of cell if the button is supposed to be in every cell , otherwise you have to add it relative to the mainView (self.view)

Related

UILabels and UICollectionView inside of UITableViewCell - need dynamic height

I have a custom UITableViewCell class that contains various UILabels, UIButtons, and a UITextField in the top and mid-sections, and then a UICollectionView at the bottom.
As a user enters more search terms into the UICollectionView, the collection view grows vertically, but I can't get my TableViewCell to adjust its height dynamically.
I have added constraints for every item in the TableViewCell so AutoLayout should work. I even set the heightForRowAt function to return UITableView.automaticDimension. But I'm apparently still missing something.
When the user adds/subtracts items to the collection view, how can I have the TableViewCell update its height dynamically?
I also tried the following block, but it doesn't work either.
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
collectionView.layoutIfNeeded()
collectionView.frame = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height + titleLabel.frame.height + filterButton.frame.height + collectionView.frame.height)
return collectionView.frame.size
}

TextFields not responding in Collection View Cell

I am trying to create a Collection View, which is somewhat like this...collection view -> 2 cells(vertically placed on screen) -> each cell contains some textFields -> click on the textField and enter your inputs.
I have added the textfields in the collection view cell file, and the cell is being called in a CollectionViewController. The problem is, the textfield are coming up fine on the UI part, but are not responding to touch. How can I solve this?
this is in a CollectionViewCell File (class AddressCollectionViewCell: UICollectionViewCell)
setTextFieldDelegates()
backgroundColor = .clear
contentView.addSubview(containerView)
containerView.backgroundColor = UIColor.black
containerView.fillSuperview()
//containerView.heightAnchor.constraint(equalToConstant: 600)
containerView.addSubview(addressStackView)
addressStackView.anchor(containerView.topAnchor, left: containerView.leftAnchor, right: containerView.rightAnchor, topConstant: 12, leftConstant: 12)
addTitleLabel()`
addTextFieldsToStackView()
func addTextFieldsToStackView() {
addressStackView.addArrangedSubview(houseTextField )
addressStackView.addArrangedSubview(pincodeTextField)
addressStackView.addArrangedSubview(localityTextField )
addressStackView.addArrangedSubview(areaTextField)
addressStackView.addArrangedSubview(addressLineOneTextField))
addressStackView.addArrangedSubview(cityTextField)
addressStackView.addArrangedSubview(stateTextField)
}

UIButton is changing other UIButton's in collectionView cell, how do I prevent this?

I've created a custom collectionView cell class that contains a UIButton. So each cell contains it's own button that a user can press. However whenever one cell button is tapped it causes background color changes to buttons in other cells. I want it to where only the selected button's background color is changed instead and to prevent the change to other buttons. Below is my code:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as! SubjectsCell
cell.subjectButton.setTitle(subjectNames[indexPath.row], for: .normal)
cell.subjectButton.addTarget(self, action: #selector(updateBackgroundColor(_:)), for: .touchUpInside)
if cell.subjectButton.isChosen == selectedState{
cell.subjectButton.backgroundColor = .green }
else if cell.subjectButton.isChosen != selectedState {
cell.subjectButton.backgroundColor = UIColor(red: 34.0/255.0, green: 210.0/255.0, blue: 255.0/255.0, alpha: 1)
}
return cell
I realize that dequeueReusableCell causes some cells to be reused, if this is my problem how I prevent cell changes happening to random cell's and only affect the cell that the tapped button is in.
You're right that dequeueReusableCell(withReuseIdentifier:for:) is the source of the issue here! You just need to have your cell class override UICollectionReusableView's prepareForReuse() method and reset the background to whatever it needs to be.
You may need to change your data model so you have a way of remembering which cells have had the button pressed since the cells can't hold on to that data without causing problems.
Also note that calling addTarget inside that collectionView(_:cellForItemAt:) may cause problems later, targets are typically only added once when the object is set up initially. To avoid issues you should set that up either in the nib / storyboard as an action, or when you setup the view objects if you're doing programmatic view setup.
Here's Apple's documentation on prepareForReuse().
You can do something like this:
class SubjectsCell : UICollectionViewCell
{
#IBAction func buttonAction(_ sender: UIButton) {
updateBackgroundColor()
}
}
so the cell view background update should present in SubjectsCell because its a view update not in job of viewController.

UITableviewCell showing old data and new data on reload

I have a UITableViewCell and I am adding xib in cellForRowIndexPath method. It works fine until I update the model and call reloadData on UITableView. The cell is showing new data on top of the old data, I can see the label on the old label text.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let customView:CustomView = UIView.fromNib()
userView.frame = CGRect(x: 10, y: y, width: Int(self.tableView.bounds.size.width-50), height: 50)
userView.label.text = data[indexPath.row]
cell.addSubview(customView:)
Any guesses why this could happen?
The quick answer is this: since cells are reused when dequeued, you are adding a new CustomView to a cell that already had a CustomView added when dequeued previously.
One way you could handle this is to remove any existing CustomView from the hierarchy before creating a new one and adding it. To do this you could add a recognizable tag to the view each time, and then look for a view with that same tag to remove during your dequeue process, like this:
//Remove existing view, if it exists
if let existingView = cell.viewWithTag(999) {
//A view was found - so remove it.
existingView.removeFromSuperview()
}
let customView: CustomView = UIView.fromNib()
//Set a tag so it can be removed in the future
customView.tag = 999
customView.frame = CGRect(x: 10, y: y, width: Int(self.tableView.bounds.size.width-50), height: 50)
customView.label.text = data[indexPath.row]
cell.addSubview(customView)
To me this feels like overkill, as it seems you should just add your customView to a custom UICollectionViewCell so you aren't essentially creating a custom cell on the fly, but that is just me. If you did this you could simply dequeue your custom cell and set the text on the label without having to add more views to the hierarchy all the time.

How to increase the UITableView separator height?

I want more space(10px) between each cell. How can I do this?
And I have added this code
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
The best way for me, just add this in cellForRowAtIndexPath or in willDisplayCell
CGRect sizeRect = [UIScreen mainScreen].applicationFrame;
NSInteger separatorHeight = 3;
UIView * additionalSeparator = [[UIView alloc] initWithFrame:CGRectMake(0,cell.frame.size.height-separatorHeight,sizeRect.size.width,separatorHeight)];
additionalSeparator.backgroundColor = [UIColor grayColor];
[cell addSubview:additionalSeparator];
For Swift 3.0:
let screenSize = UIScreen.main.bounds
let separatorHeight = CGFloat(3.0)
let additionalSeparator = UIView.init(frame: CGRect(x: 0, y: self.frame.size.height-separatorHeight, width: screenSize.width, height: separatorHeight))
additionalSeparator.backgroundColor = UIColor.gray
self.addSubview(additionalSeparator)
You should add this to cell's method awakeFromNib() to avoid re-creation.
I have seen many clunky solutions like subclassing UITableView with hidden cells, and other less optimal ones incl. in this thread.
When initializing the UITableView, Set the rowHeight property of UITableView to a height that equals = cell height + desired separator/space height.
Do not use standard UITableViewCell class though, instead, subclass the UITableViewCell class and override its layoutSubviews method. There, after calling super (don't forget that), set the height of the cell itself to desired height.
BONUS UPDATE 18/OCT/2015:
You can be a bit smart about this. The solution above basically puts the "separator" at the bottom of the cell. What really happens is, the row height is managed by the TableViewController but the cell is resized to be a bit lower. This results in the separator/empty space being at the bottom. But you can also centre all the subviews vertically so that you leave the same space at the top and the bottom. For example 1pt and 1pt.
You can also create isFirst, isLast convenience properties on your cell subclass. You would set these to yes in the cellForRowAtIndexPath.
This way you can handle the edge cases for top and bottom separators inside the layoutSubviews method as this would have access to these properties.
This way you can handle the edge cases for top or bottom - because sometimes the design department wants N+1 separators while the number of cells is only N. So you have to either deal with the top one or the boot one in a special way. But it's best do this inside cells instead tableViewHeader or TableViewFooter.
I don't think it's possible using standard API. I guess you would need to subclass the UITableViewCell and add a view that simulates a separator at the bottom of the cell.
You may want to check this question, it seems related and has some sample code:
iPhone + UITableView + place an image for separator
In Swift
The easiest and shortest way for me was to add the snippet below in cellForRowAtIndexPath or in willDisplayCell:
override func tableView(tableView: UITableView,
willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath)
{
let additionalSeparatorThickness = CGFloat(3)
let additionalSeparator = UIView(frame: CGRectMake(0,
cell.frame.size.height - additionalSeparatorThickness,
cell.frame.size.width,
additionalSeparatorThickness))
additionalSeparator.backgroundColor = UIColor.redColor()
cell.addSubview(additionalSeparator)
}
this is quite old. Nevertheless I will post my approach.
Simply increase your cell height a bit and assign a mask layer to the cell, like that:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "...", for: indexPath)
// Configure the cell...
let maskLayer = CAShapeLayer()
let bounds = cell.bounds
maskLayer.path = UIBezierPath(roundedRect: CGRect(x: 2, y: 2, width: bounds.width-4, height: bounds.height-4), cornerRadius: 5).cgPath
cell.layer.mask = maskLayer
return cell
}
So in this example my seperator height will be 4.
Have fun!
You can do this entirely in the storyboard. Here is how:
go to the storyboard and select the tableview
Show the Size Inspector and from there set row height to say 140.
then show the Attributes Inspector and from there set your separator to Single Line and Style Plain and choose a color
then in the storyboard (or in Document Outline) select the cell
and again in the Size Inspector, under the Table View Cell, set custom Row Height to say 120.
That’s all. Your separator will be 20 units tall.
Kinda old thread, but since I only found hacky solutions in this thread,
here the solution that worked best for me (without additional UIView in every cell)
Swift 3:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//configure your cell...
cell.layer.shadowColor = UIColor.red.cgColor
cell.layer.shadowOffset = CGSize(width: 0, height: 1)
cell.layer.shadowOpacity = 1
cell.layer.shadowRadius = 0
cell.layer.masksToBounds = false
return cell
}
EDIT: Unfortunately this does not work if you scroll up in a table. I leave the answer here anyway, since it might be a solution if your table has limited content.
See Shadow on a UITableViewCell disappears when scrolling for more info.
For a table cell with height of 50 and a space of 5 pix between the rows. Width is 320.
Define the background of the cells to be clear:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = [UIColor clearColor];
}
Set the height of the cells, this is the size of the row PLUS the delimiter:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 55;
}
And define in cellForRowAtIndexPath a box, with the size of the row (MINUS delimiter) to draw in the background color:
UILabel *headerBackgroundLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,320,50)];
backgroundBox.backgroundColor = [UIColor grayColor];
[cell addSubview:backgroundBox];
I do it a much simpler and more flexible way. Some may call it a hack. I call it pragmatic.
I hide the standard UITableViewSeparator. I then add a subview to my cell, using auto layout pin it to the top. Fix the height to what I desire. Pin it to the edges with a margin either side. Change it's background colour. I have a plain separator with the height i desire.
You may question how efficient this is having another UIView in the cell hierarchy. Is it really going to make a noticeable difference? Probably not - you've just taken the standard separator out of the table hierarchy anyway.
Swift 4
It's not possible to make the default separator higher. Instead you need to add a subview that will look as a separator to each cell (and optionally make the cell higher). You can do it for example in cellForRowAtIndexPath or in a UITableViewCell subclass.
In case you allow to select the cell, you need to add the subview for selected state as well, otherwise the separator would disappear when the cell is selected. That's why selectedBackgroundView is also configured.
Add this into your UITableViewController subclass:
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorStyle = .none
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.backgroundView = UIView(backgroundColor: .white)
cell.backgroundView?.addSeparator()
cell.selectedBackgroundView = UIView(backgroundColor: .blue)
cell.selectedBackgroundView?.addSeparator()
// configure the cell
return cell
}
Add this extensions into the same file at the bottom:
private extension UIView {
convenience init(backgroundColor: UIColor) {
self.init()
self.backgroundColor = backgroundColor
}
func addSeparator() {
let separatorHeight: CGFloat = 2
let frame = CGRect(x: 0, y: bounds.height - separatorHeight, width: bounds.width, height: separatorHeight)
let separator = UIView(frame: frame)
separator.backgroundColor = .gray
separator.autoresizingMask = [.flexibleTopMargin, .flexibleWidth]
addSubview(separator)
}
}
Here's an option that might work for some people
cell.layer.borderColor = UIColor.white.cgColor
cell.layer.borderWidth = 4.0
cell.layer.masksToBounds = true
The easier and safest solution to this problem is to turn off the table separator and use a UITableViewCell as a separator of variable height. Sure, you'll have to do some index math to figure out where items are, but really it's odd / even.
It won't break and you get the benefit of recyclable cells (no extraneous views to clean up).
First make tableview separator none from the storyboard. Then add UILabel/UIView at bottom of cell of height(you needed) using storyboard or Xib
For Swift 4
Implemented King-Wizard's solution to Swift 4:
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let additionalSeparatorThickness = CGFloat(4)
let additionalSeparator = UIView(frame: CGRect(x: 0,
y: cell.frame.size.height - additionalSeparatorThickness, width: cell.frame.size.width, height: additionalSeparatorThickness))
additionalSeparator.backgroundColor = UIColor.groupTableViewBackground
cell.addSubview(additionalSeparator)
}
This is the easiest solution I've found:
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
" "
}
then just set the height to whatever you want:
tableView.sectionHeaderHeight = 30.0
I came across a way that has allowed me to effectively change the gap between cells.
In Interface builder I set the row height to be 46.
In the cellForRowAtIndexPath method of my TableView delegate I set the frame of the cell to be a smaller value.
cell.frame=CGRectMake(44,0,tableView.bounds.size.width,44)
This gives me a cell with a height of 44 that fits the width of the tableView but the space provided for the row will be 46 as defined in IB.
I was filling the cell programmatically anyway so this suited me fine.
You should implement
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
delegate method. and return 100.0 there.