Place UILabel center of parent - ios

I am trying to put UILable at the center of each cell of UICollectionView.
Here is my code:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
// Configure the cell
cell.backgroundColor = UIColor.brownColor()
let title = UILabel(frame: CGRectMake(cell.bounds.midX, cell.bounds.midY, cell.bounds.size.width, 20)) //
title.text = "ddd"
title.textColor = UIColor.whiteColor()
// title.center = cell.center
cell.contentView.addSubview(title)
// let xCenterConstraint = NSLayoutConstraint(item: title, attribute: .CenterX, relatedBy: .Equal, toItem: cell, attribute: .CenterX, multiplier: 1, constant: 0)
// let yCenterConstraint = NSLayoutConstraint(item: title, attribute: .CenterY, relatedBy: .Equal, toItem: cell, attribute: .CenterY, multiplier: 1, constant: 0)
// let leadingConstraint1 = NSLayoutConstraint(item: title, attribute: .Leading, relatedBy: .Equal, toItem: cell, attribute: .Leading, multiplier: 1, constant: 20)
// let trailingConstraint1 = NSLayoutConstraint(item: title, attribute: .Trailing, relatedBy: .Equal, toItem: cell, attribute: .Trailing, multiplier: 1, constant: -20)
// cell.addConstraints([xCenterConstraint, yCenterConstraint, leadingConstraint1, trailingConstraint1])
// title.centerXAnchor.constraintEqualToAnchor(cell.centerXAnchor).active = true
// title.centerYAnchor.constraintEqualToAnchor(cell.centerYAnchor).active = true
return cell
}
The output:
Seems I need to change my code, so what am I missing?

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
// Configure the cell
cell.backgroundColor = UIColor.brownColor()
//Editing Starts
let title = UILabel(frame: CGRectMake(cell.bounds.midX -(cell.bounds.size.width/2) , cell.bounds.midY - 10, cell.bounds.size.width, 20))
//Editing Ends
//
title.text = "ddd"
title.textColor = UIColor.whiteColor()
// title.center = cell.center
cell.contentView.addSubview(title)
// let xCenterConstraint = NSLayoutConstraint(item: title, attribute: .CenterX, relatedBy: .Equal, toItem: cell, attribute: .CenterX, multiplier: 1, constant: 0)
// let yCenterConstraint = NSLayoutConstraint(item: title, attribute: .CenterY, relatedBy: .Equal, toItem: cell, attribute: .CenterY, multiplier: 1, constant: 0)
// let leadingConstraint1 = NSLayoutConstraint(item: title, attribute: .Leading, relatedBy: .Equal, toItem: cell, attribute: .Leading, multiplier: 1, constant: 20)
// let trailingConstraint1 = NSLayoutConstraint(item: title, attribute: .Trailing, relatedBy: .Equal, toItem: cell, attribute: .Trailing, multiplier: 1, constant: -20)
// cell.addConstraints([xCenterConstraint, yCenterConstraint, leadingConstraint1, trailingConstraint1])
// title.centerXAnchor.constraintEqualToAnchor(cell.centerXAnchor).active = true
// title.centerYAnchor.constraintEqualToAnchor(cell.centerYAnchor).active = true
return cell
}

Try following code it may helps you
let title = UILabel(frame: CGRectMake(0, 0, cell.bounds.size.width, 20))
title.textAlignment=.Center
title.text = "ddd"
title.textColor = UIColor.whiteColor()
title.center = cell.contentView.center
cell.contentView.addSubview(title)

Related

Why UITableViewCell dynamic view constraint not working properly?

I am trying to create UIButton inside the UITableViewCell using following way
UITableView configuration :
self.tableView.estimatedRowHeight = 1
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.delegate = self
self.tableView.dataSource = self
UITableViewCell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let uiTableViewCell = UITableViewCell(style: .default, reuseIdentifier: "More");
uiTableViewCell.contentView.backgroundColor = .yellow
let moreBtn = UIButton(type: .system)
moreBtn.setTitle("More", for: .normal)
moreBtn.setTitleColor(.white, for: .normal)
moreBtn.backgroundColor = UIColor.init(hexString: "#2A1771")
moreBtn.translatesAutoresizingMaskIntoConstraints = false
uiTableViewCell.contentView.addSubview(moreBtn)
let leading = NSLayoutConstraint(item: moreBtn, attribute: .leading, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .leading, multiplier: 1, constant: 16)
let trailing = NSLayoutConstraint(item: moreBtn, attribute: .trailing, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .trailing, multiplier: 1, constant: 16)
let top = NSLayoutConstraint(item: moreBtn, attribute: .top, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .top, multiplier: 1, constant: 16)
let bottom = NSLayoutConstraint(item: moreBtn, attribute: .bottom, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .bottom, multiplier: 1, constant: 16)
let height = NSLayoutConstraint(item: moreBtn, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 52)
uiTableViewCell.contentView.addConstraints([leading,top,trailing,bottom,height])
NSLayoutConstraint.activate([leading,top,trailing,bottom,height])
return uiTableViewCell
}
See this following image.. Why more button going outside from contentView
Your constraints are saying the the button's trailing edge should be 16 more than the content view trailing edge (The constant is +16) and similarly for the bottom edge.
You can either swap the item and toItem properties in those constraints or use -16 as the constant.
You will also have a problem with adding the button in cellForRow as cells are reused when the table view scrolls, resulting in multiple buttons being added to a cell. You should add the button in the cell itself, either in the initialiser or in awakeFromNib

Applying a shadow to a subview loaded from nib

I am loading a custom view class from the nib at viewWillAppear. After loading the nib, I add it as a subview, then apply some constraints, then update the constraints. At that point I attempt to add a shadow to this view, but no shadow is displaying....
Just for some context, the ViewController has scrollview that contains a contentView. All of the view's content goes inside this contentView.
Here is my code:
ViewController
class MyViewController: UIViewController {
#IBOutlet weak var contentView: UIView!
var matches: [Match] = []
var matchViews: [MatchDetailsView] = []
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setMatches()
}
func setMatches() {
// Match One
let matchOneDetailsView = MatchDetailsView.instanceFromNib(match: matches.count > 0 ? matches[0] : nil, delegate: self, tag: 1)
contentView.addSubview(matchOneDetailsView)
matchOneDetailsView.translatesAutoresizingMaskIntoConstraints = false
let matchOneLeadingConstraint = NSLayoutConstraint(item: matchOneDetailsView, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 16)
let matchOneTrailingConstraint = NSLayoutConstraint(item: matchOneDetailsView, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: -16)
let matchOneTopConstraint = NSLayoutConstraint(item: matchOneDetailsView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 32)
// Match Two
let matchTwoDetailsView = MatchDetailsView.instanceFromNib(match: matches.count > 1 ? matches[1] : nil, delegate: self, tag: 2)
contentView.addSubview(matchTwoDetailsView)
matchTwoDetailsView.translatesAutoresizingMaskIntoConstraints = false
let matchTwoLeadingConstraint = NSLayoutConstraint(item: matchTwoDetailsView, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 16)
let matchTwoTrailingConstraint = NSLayoutConstraint(item: matchTwoDetailsView, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: -16)
let matchTwoTopConstraint = NSLayoutConstraint(item: matchTwoDetailsView, attribute: .top, relatedBy: .equal, toItem: matchOneDetailsView, attribute: .bottom, multiplier: 1, constant: 32)
// Match Three
let matchThreeDetailsView = MatchDetailsView.instanceFromNib(match: matches.count > 2 ? matches[2] : nil, delegate: self, tag: 3)
contentView.addSubview(matchThreeDetailsView)
matchThreeDetailsView.translatesAutoresizingMaskIntoConstraints = false
let matchThreeLeadingConstraint = NSLayoutConstraint(item: matchThreeDetailsView, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 16)
let matchThreeTrailingConstraint = NSLayoutConstraint(item: matchThreeDetailsView, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: -16)
let matchThreeTopConstraint = NSLayoutConstraint(item: matchThreeDetailsView, attribute: .top, relatedBy: .equal, toItem: matchTwoDetailsView, attribute: .bottom, multiplier: 1, constant: 32)
let matchThreeBottomConstraint = NSLayoutConstraint(item: matchThreeDetailsView, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: -32)
NSLayoutConstraint.activate([matchOneLeadingConstraint, matchOneTrailingConstraint, matchOneTopConstraint, matchTwoLeadingConstraint, matchTwoTrailingConstraint, matchTwoTopConstraint, matchThreeLeadingConstraint, matchThreeTrailingConstraint, matchThreeTopConstraint, matchThreeBottomConstraint])
updateViewConstraints()
matchViews.append(matchOneDetailsView)
matchViews.append(matchTwoDetailsView)
matchViews.append(matchThreeDetailsView)
styleMatchViews()
}
func styleMatchViews() {
for view in matchViews {
view.addShadow(opacity: 0.25, yOffset: 0, xOffset: 0, radius: 5.0)
view.roundCorners(withRadius: 5.0)
}
}
}
MatchDetailsView
class MatchDetailsView: UIView {
class func instanceFromNib(match: Match?, delegate: MatchDetailsViewDelegate, tag: Int) -> MatchDetailsView {
let view = UINib(nibName: "MatchDetailsView", bundle: nil).instantiate(withOwner: MatchDetailsView(), options: nil)[0] as! MatchDetailsView
view.translatesAutoresizingMaskIntoConstraints = false
view.updateMatchContent()
return view
}
}
UIViewExtension
extension UIView {
/**
Add Shadow
Puts a Drop Shadow in the UIView
*/
func addShadow(opacity: Float, yOffset: Int, xOffset: Int, radius: CGFloat) {
self.layer.masksToBounds = false
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = opacity
self.layer.shadowOffset = CGSize(width: xOffset, height: yOffset)
self.layer.shadowRadius = radius
self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
}
}
If MatchDetailsView's nib file has 'clipsToBounds' set to false, why isn't my shadow showing up when the page is loaded? Am I missing a layout function even though they seem to be laid out correctly?
You are setting the .shadowPath to the bounds of the view... but the bounds at that point may not be (probably will not be) the bounds after auto-layout lays out the views.
For a "shadowed view" you are much better off setting the shadow inlayoutSubviews() inside the view itself.
You should also add and setup your subviews in viewDidLoad() viewWillAppear() may be called more than once (depending on your navigation), and you'll end up adding multiple copies of your subviews.
So...
Change your MatchDetailsView class like this:
class MatchDetailsView: UIView {
var opacity: CGFloat = 0.0
var xOffset: CGFloat = 0.0
var yOffset: CGFloat = 0.0
// for the shadowRadius
var sRadius: CGFloat = 0.0
// for the cornerRadius
var cRadius: CGFloat = 0.0
override func layoutSubviews() {
self.layer.masksToBounds = false
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = Float(opacity)
self.layer.shadowOffset = CGSize(width: xOffset, height: yOffset)
self.layer.shadowRadius = sRadius
self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
self.layer.cornerRadius = cRadius
}
class func instanceFromNib(match: Match?, delegate: MatchDetailsViewDelegate, tag: Int) -> MatchDetailsView {
let view = UINib(nibName: "MatchDetailsView", bundle: nil).instantiate(withOwner: MatchDetailsView(), options: nil)[0] as! MatchDetailsView
view.translatesAutoresizingMaskIntoConstraints = false
view.updateMatchContent()
return view
}
}
Then, in your view controller:
override func viewDidLoad() {
super.viewDidLoad()
setMatches()
}
func setMatches() {
// Match One
let matchOneDetailsView = MatchDetailsView.instanceFromNib(match: matches.count > 0 ? matches[0] : nil, delegate: self, tag: 1)
contentView.addSubview(matchOneDetailsView)
matchOneDetailsView.translatesAutoresizingMaskIntoConstraints = false
let matchOneLeadingConstraint = NSLayoutConstraint(item: matchOneDetailsView, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 16)
let matchOneTrailingConstraint = NSLayoutConstraint(item: matchOneDetailsView, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: -16)
let matchOneTopConstraint = NSLayoutConstraint(item: matchOneDetailsView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 32)
// Match Two
let matchTwoDetailsView = MatchDetailsView.instanceFromNib(match: matches.count > 1 ? matches[1] : nil, delegate: self, tag: 2)
contentView.addSubview(matchTwoDetailsView)
matchTwoDetailsView.translatesAutoresizingMaskIntoConstraints = false
let matchTwoLeadingConstraint = NSLayoutConstraint(item: matchTwoDetailsView, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 16)
let matchTwoTrailingConstraint = NSLayoutConstraint(item: matchTwoDetailsView, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: -16)
let matchTwoTopConstraint = NSLayoutConstraint(item: matchTwoDetailsView, attribute: .top, relatedBy: .equal, toItem: matchOneDetailsView, attribute: .bottom, multiplier: 1, constant: 32)
// Match Three
let matchThreeDetailsView = MatchDetailsView.instanceFromNib(match: matches.count > 2 ? matches[2] : nil, delegate: self, tag: 3)
contentView.addSubview(matchThreeDetailsView)
matchThreeDetailsView.translatesAutoresizingMaskIntoConstraints = false
let matchThreeLeadingConstraint = NSLayoutConstraint(item: matchThreeDetailsView, attribute: .leading, relatedBy: .equal, toItem: contentView, attribute: .leading, multiplier: 1, constant: 16)
let matchThreeTrailingConstraint = NSLayoutConstraint(item: matchThreeDetailsView, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: -16)
let matchThreeTopConstraint = NSLayoutConstraint(item: matchThreeDetailsView, attribute: .top, relatedBy: .equal, toItem: matchTwoDetailsView, attribute: .bottom, multiplier: 1, constant: 32)
let matchThreeBottomConstraint = NSLayoutConstraint(item: matchThreeDetailsView, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: -32)
NSLayoutConstraint.activate([matchOneLeadingConstraint, matchOneTrailingConstraint, matchOneTopConstraint, matchTwoLeadingConstraint, matchTwoTrailingConstraint, matchTwoTopConstraint, matchThreeLeadingConstraint, matchThreeTrailingConstraint, matchThreeTopConstraint, matchThreeBottomConstraint])
matchViews.append(matchOneDetailsView)
matchViews.append(matchTwoDetailsView)
matchViews.append(matchThreeDetailsView)
styleMatchViews()
}
func styleMatchViews() {
for view in matchViews {
view.opacity = 0.25
view.yOffset = 0.0
view.xOffset = 0.0
view.sRadius = 5.0
view.cRadius = 5.0
}
}

UIView appearing from left and disappearing from right Animation

I have a UITableView with custom sections programatically done. I am aiming to have a button in the navigation bar that will trigger a functions that will show or will hide a UIView with an appearing from left and disappearing from right Animation. So far:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
/** Header View **/
let headerView = UITableViewHeaderFooterView()
headerView.backgroundColor = UIColor.VinylRecorderTheme.white
headerView.addBottomBorder(color: UIColor.init(red: 250/255, green: 250/255, blue: 250/255, alpha: 1), height: 1, margins: 0)
headerView.tag = section
headerView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(headerViewTouched)))
/* Header ImageView */
let headerImageView = UIImageView()
if let imageForHeader = vinylRecorderHelper.loadThimbnailFromMetadata(url: iCloudAlbumArray[section].urlTrackArray[0].url){
headerImageView.image = imageForHeader
}
else{
headerImageView.image = UIImage(named: "music_album_ic")
}
headerView.addSubview(headerImageView)
headerImageView.translatesAutoresizingMaskIntoConstraints = false
headerView.addConstraint(NSLayoutConstraint(item: headerImageView, attribute: .leading, relatedBy: .equal, toItem: headerView, attribute: .leading, multiplier: 1, constant: 8))
headerView.addConstraint(NSLayoutConstraint(item: headerImageView, attribute: .centerY, relatedBy: .equal, toItem: headerView, attribute: .centerY, multiplier: 1, constant: 0))
headerView.addConstraint(NSLayoutConstraint(item: headerImageView, attribute: .height, relatedBy: .equal, toItem: headerView, attribute: .height, multiplier: 0.65, constant: 0))
headerView.addConstraint(NSLayoutConstraint(item: headerImageView, attribute: .width, relatedBy: .equal, toItem: headerImageView, attribute: .height, multiplier: 1, constant: 0))
/** Header Button **/
let buttonWidth = currentDeviceTraitStatus == .wreghreg ? CGFloat(34):CGFloat(16)
let headerExpandButton = UIButton()
headerExpandButton.translatesAutoresizingMaskIntoConstraints = false
headerExpandButton.contentMode = .scaleAspectFit
headerExpandButton.setImage(#imageLiteral(resourceName: "arrow_rigth_ic"), for: .normal)
headerExpandButton.setImage(#imageLiteral(resourceName: "arrow_down_ic"), for: .selected)
headerExpandButton.tag = expandButtonTag
headerView.addSubview(headerExpandButton)
headerView.addConstraint(NSLayoutConstraint(item: headerExpandButton, attribute: .trailing, relatedBy: .equal, toItem: headerView, attribute: .trailing, multiplier: 1, constant: -8))
headerView.addConstraint(NSLayoutConstraint(item: headerExpandButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: buttonWidth))
headerView.addConstraint(NSLayoutConstraint(item: headerExpandButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: buttonWidth))
headerView.addConstraint(NSLayoutConstraint(item: headerExpandButton, attribute: .centerY, relatedBy: .equal, toItem: headerView, attribute: .centerY, multiplier: 1, constant: 0))
/** Header Label **/
let headerNameLabel = UILabel()
headerNameLabel.text = "\(iCloudAlbumArray[section].artistName) - \(iCloudAlbumArray[section].albumName)"
headerNameLabel.font = currentDeviceTraitStatus == .wreghreg ? .boldSystemFont(ofSize: 18):.boldSystemFont(ofSize: 15)
headerView.addSubview(headerNameLabel)
headerNameLabel.translatesAutoresizingMaskIntoConstraints = false
headerView.addConstraint(NSLayoutConstraint(item: headerNameLabel, attribute: .left, relatedBy: .equal, toItem: headerImageView, attribute: .right, multiplier: 1, constant: 8))
headerView.addConstraint(NSLayoutConstraint(item: headerNameLabel, attribute: .top, relatedBy: .equal, toItem: headerView, attribute: .top, multiplier: 1, constant: 0))
headerView.addConstraint(NSLayoutConstraint(item: headerNameLabel, attribute: .bottom, relatedBy: .equal, toItem: headerView, attribute: .bottom, multiplier: 1, constant: 0))
headerView.addConstraint(NSLayoutConstraint(item: headerExpandButton, attribute: .leading, relatedBy: .equal, toItem: headerNameLabel, attribute: .trailing, multiplier: 1, constant: 8))
/** Remove Button Label **/
let removeButton = UIButton()
removeButton.backgroundColor = UIColor.VinylRecorderTheme.redApple
removeButton.tag = deleteButtonTag
headerView.addSubview(removeButton)
removeButton.translatesAutoresizingMaskIntoConstraints = false
headerView.addConstraint(NSLayoutConstraint(item: removeButton, attribute: .leading, relatedBy: .equal, toItem: headerView, attribute: .leading, multiplier: 1, constant: 0))
headerView.addConstraint(NSLayoutConstraint(item: removeButton, attribute: .top, relatedBy: .equal, toItem: headerView, attribute: .top, multiplier: 1, constant: 0))
headerView.addConstraint(NSLayoutConstraint(item: removeButton, attribute: .bottom, relatedBy: .equal, toItem: headerView, attribute: .bottom, multiplier: 1, constant: 0))
removeButton.widthAnchor.constraint(equalToConstant: 0).isActive = true
removeButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(removeViewTouched)))
return headerView
}
And the function that will perform the desired Animation is:
#IBAction func startStopEditAction(_ sender: UIButton) {
print("\(logClassName): startStopEditAction.")
sender.isSelected = !sender.isSelected
if let sectionView = iCloudExportsTableView.headerView(forSection: 0){
print("\(logClassName): startStopEditAction in header")
let removeButton:UIButton = sectionView.viewWithTag(deleteButtonTag) as! UIButton
//removeButton.isHidden = !removeButton.isHidden
//removeButton.widthAnchor.constraint(equalToConstant: isEditingRemove ? 60 : 0)
UIView.transition(with: view, duration: 1.5, options: .transitionCrossDissolve, animations: {
removeButton.widthAnchor.constraint(equalToConstant: 0).isActive = false
removeButton.widthAnchor.constraint(equalToConstant: 60).isActive = true
//removeButton.isHidden = !removeButton.isHidden
})
}
}
EDIT
The UIView (Button)is
let removeButton = UIButton()
After some work around I have been able to achieve what I was looking for.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
/** Header View **/
let headerView = UITableViewHeaderFooterView()
headerView.backgroundColor = UIColor.VinylRecorderTheme.white
headerView.addBottomBorder(color: UIColor.init(red: 250/255, green: 250/255, blue: 250/255, alpha: 1), height: 1, margins: 0)
headerView.tag = section
headerView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(headerViewTouched)))
**************
/** Remove Button **/
let removeButton = UIButton()
removeButton.backgroundColor = UIColor.VinylRecorderTheme.redApple
removeButton.tag = section
removeButton.setTitle(NSLocalizedString("com.messages.delete", comment: ""), for: .normal)
removeButton.titleLabel?.font = currentDeviceTraitStatus == .wreghreg ? .boldSystemFont(ofSize: 18):.boldSystemFont(ofSize: 15)
removeButton.setTitleColor(UIColor.white, for: .normal)
headerView.addSubview(removeButton)
removeButton.translatesAutoresizingMaskIntoConstraints = false
headerView.addConstraint(NSLayoutConstraint(item: removeButton, attribute: .leading, relatedBy: .equal, toItem: headerView, attribute: .leading, multiplier: 1, constant: 0))
headerView.addConstraint(NSLayoutConstraint(item: removeButton, attribute: .top, relatedBy: .equal, toItem: headerView, attribute: .top, multiplier: 1, constant: 0))
headerView.addConstraint(NSLayoutConstraint(item: removeButton, attribute: .bottom, relatedBy: .equal, toItem: headerView, attribute: .bottom, multiplier: 1, constant: 0))
let widthConstraint = NSLayoutConstraint(item: removeButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.isEditingRemove ? 90:0)
widthConstraint.identifier = tableViewSectionWidthId
headerView.addConstraint(widthConstraint)
removeButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(removeViewTouched)))
return headerView
}
And then In the IBAction:
#IBAction func startStopEditAction(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
let numberOfSections = iCloudExportsTableView.numberOfSections
for i in 0..<numberOfSections{
if let sectionView = iCloudExportsTableView.headerView(forSection: i){
let filteredConstraints = sectionView.constraints.filter { $0.identifier == tableViewSectionWidthId }
if let widthConstraint = filteredConstraints.first {
widthConstraint.constant = self.isEditingRemove ? 90:0
UIView.animate(withDuration: 0.5, delay: TimeInterval.init(Double(i) * Double(0.20)), options: UIViewAnimationOptions.curveEaseInOut, animations: {
sectionView.layoutIfNeeded()
}, completion: { (finished) in
})
}
}
}
}

Add NSLayoutConstraint for a view inside a UITableCellView

I would like to have a UIButton centred inside my UITableCellView. I've added the necessary code in the tableView cellForRowAt function but I get the error :
The view hierarchy is not prepared for the constraint: When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on
-[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug.
My code is the following :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell = UITableViewCell(
style: .default, reuseIdentifier: Id.settingButtonCellIdentifier)
cell!.backgroundColor = UIColor.clear
cell!.preservesSuperviewLayoutMargins = false
cell!.separatorInset = UIEdgeInsets.zero
let button : UIButton = UIButton(type: UIButtonType.custom) as UIButton
button.backgroundColor = UIColor.red
button.setTitle("Click Me !", for: UIControlState.normal)
cell!.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.addConstraint(NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: cell!, attribute: .leading, multiplier: 1, constant: 10))
button.addConstraint(NSLayoutConstraint(item: button, attribute: .trailing, relatedBy: .equal, toItem: cell!, attribute: .trailing, multiplier: 1, constant: 10))
button.addConstraint(NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: cell!, attribute: .top, multiplier: 1, constant: 10))
button.addConstraint(NSLayoutConstraint(item: button, attribute: .bottom, relatedBy: .equal, toItem: cell!, attribute: .bottom, multiplier: 1, constant: 10))
}
return cell!
}
Any help would be appreciated !
Try this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell = UITableViewCell(
style: .default, reuseIdentifier: Id.settingButtonCellIdentifier)
cell!.backgroundColor = UIColor.clear
cell!.preservesSuperviewLayoutMargins = false
cell!.separatorInset = UIEdgeInsets.zero
let button : UIButton = UIButton(type: UIButtonType.custom) as UIButton
button.backgroundColor = UIColor.red
button.setTitle("Click Me !", for: UIControlState.normal)
button.translatesAutoresizingMaskIntoConstraints = false
cell!.contentView.addSubview(button)
cell.contentView.addConstraint(NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: cell.contentView, attribute: .leading, multiplier: 1, constant: 10))
cell.contentView.addConstraint(NSLayoutConstraint(item: button, attribute: .trailing, relatedBy: .equal, toItem: cell.contentView, attribute: .trailing, multiplier: 1, constant: 10))
cell.contentView.addConstraint(NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: cell.contentView, attribute: .top, multiplier: 1, constant: 10))
cell.contentView.addConstraint(NSLayoutConstraint(item: button, attribute: .bottom, relatedBy: .equal, toItem: cell.contentView, attribute: .bottom, multiplier: 1, constant: 10))
}
return cell!
}

How can I make the type emoji or type anything

I am currently working on a custom keyboard
and I encountered a problem when I try to combine the textDocumentProxy in a new window
So have add emoji keyboard button
  and which I pass page with the addition of two buttons of emoji Now my problem is how I can incorporate textDocumentProxy another window or link between them waned even can type emoji
I try to type anything not only emoji
Full source code is here
https://github.com/archagon/tasty-imitation-keyboard
import UIKit
class DefaultSettings1: ExtraView, UITableViewDelegate {
#IBOutlet var tableView1: UITableView?
#IBOutlet var effectsView: UIVisualEffectView?
#IBOutlet var backButton1: UIButton?
#IBOutlet var settingsLabel: UILabel?
#IBOutlet var pixelLine: UIView?
#IBOutlet var keyPressed: UIButton?
override var darkMode: Bool {
didSet {
self.updateAppearance(darkMode)
}
}
let cellBackgroundColorDark = UIColor.whiteColor().colorWithAlphaComponent(CGFloat(0.25))
let cellBackgroundColorLight = UIColor.whiteColor().colorWithAlphaComponent(CGFloat(1))
let cellLabelColorDark = UIColor.whiteColor()
let cellLabelColorLight = UIColor.blackColor()
let cellLongLabelColorDark = UIColor.lightGrayColor()
let cellLongLabelColorLight = UIColor.grayColor()
// TODO: these probably don't belong here, and also need to be localized
required init(globalColors: GlobalColors.Type?, darkMode: Bool, solidColorMode: Bool) {
super.init(globalColors: globalColors, darkMode: darkMode, solidColorMode: solidColorMode)
self.loadNib()
}
required init(coder aDecoder: NSCoder) {
fatalError("loading from nib not supported")
}
func loadNib() {
let assets = NSBundle(forClass: self.dynamicType).loadNibNamed("DefaultSettings1", owner: self, options: nil)
if assets.count > 0 {
if var rootView = assets.first as? UIView {
rootView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(rootView)
let left = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
self.addConstraint(left)
self.addConstraint(right)
self.addConstraint(top)
self.addConstraint(bottom)
}
}
self.tableView1?.registerClass(DefaultSettings1TableViewCell.self, forCellReuseIdentifier: "cell")
self.tableView1?.estimatedRowHeight = 44;
self.tableView1?.rowHeight = UITableViewAutomaticDimension;
// XXX: this is here b/c a totally transparent background does not support scrolling in blank areas
self.tableView1?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.01)
self.updateAppearance(self.darkMode)
}
func tableView1(tableView1: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if var cell = tableView1.dequeueReusableCellWithIdentifier("cell") as? DefaultSettings1TableViewCell {
if cell.sw.allTargets().count == 0 {
cell.sw.addTarget(self, action: Selector("toggleSetting1:"), forControlEvents: UIControlEvents.ValueChanged)
}
cell.backgroundColor = (self.darkMode ? cellBackgroundColorDark : cellBackgroundColorLight)
cell.label.textColor = (self.darkMode ? cellLabelColorDark : cellLabelColorLight)
cell.longLabel.textColor = (self.darkMode ? cellLongLabelColorDark : cellLongLabelColorLight)
cell.changeConstraints()
return cell
}
else {
assert(false, "this is a bad thing that just happened")
return UITableViewCell()
}
}
func updateAppearance(dark: Bool) {
if dark {
self.effectsView?.effect
let blueColor = UIColor(red: 135/CGFloat(255), green: 206/CGFloat(255), blue: 250/CGFloat(255), alpha: 1)
self.pixelLine?.backgroundColor = blueColor.colorWithAlphaComponent(CGFloat(0.5))
self.backButton1?.setTitleColor(blueColor, forState: UIControlState.Normal)
self.settingsLabel?.textColor = UIColor.whiteColor()
if let visibleCells = self.tableView1?.visibleCells() {
for cell in visibleCells {
if var cell = cell as? UITableViewCell {
cell.backgroundColor = cellBackgroundColorDark
var label = cell.viewWithTag(2) as? UILabel
label?.textColor = cellLabelColorDark
var longLabel = cell.viewWithTag(3) as? UITextView
longLabel?.textColor = cellLongLabelColorDark
}
}
}
}
else {
let blueColor = UIColor(red: 0/CGFloat(255), green: 122/CGFloat(255), blue: 255/CGFloat(255), alpha: 1)
self.pixelLine?.backgroundColor = blueColor.colorWithAlphaComponent(CGFloat(0.5))
self.backButton1?.setTitleColor(blueColor, forState: UIControlState.Normal)
self.settingsLabel?.textColor = UIColor.grayColor()
if let visibleCells = self.tableView1?.visibleCells() {
for cell in visibleCells {
if var cell = cell as? UITableViewCell {
cell.backgroundColor = cellBackgroundColorLight
var label = cell.viewWithTag(2) as? UILabel
label?.textColor = cellLabelColorLight
var longLabel = cell.viewWithTag(3) as? UITextView
longLabel?.textColor = cellLongLabelColorLight
}
}
}
}
}
}
class DefaultSettings1TableViewCell: UITableViewCell {
var sw: UISwitch
var label: UILabel
var longLabel: UITextView
var constraintsSetForLongLabel: Bool
var cellConstraints: [NSLayoutConstraint]
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
self.sw = UISwitch()
self.label = UILabel()
self.longLabel = UITextView()
self.cellConstraints = []
self.constraintsSetForLongLabel = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.sw.setTranslatesAutoresizingMaskIntoConstraints(false)
self.label.setTranslatesAutoresizingMaskIntoConstraints(false)
self.longLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
self.longLabel.text = nil
self.longLabel.scrollEnabled = false
self.longLabel.selectable = false
self.longLabel.backgroundColor = UIColor.clearColor()
self.sw.tag = 1
self.label.tag = 2
self.longLabel.tag = 3
self.addSubview(self.sw)
self.addSubview(self.label)
self.addSubview(self.longLabel)
self.addConstraints()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addConstraints() {
let margin: CGFloat = 8
let sideMargin = margin * 2
let hasLongText = self.longLabel.text != nil && !self.longLabel.text.isEmpty
if hasLongText {
let switchSide = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: -sideMargin)
let switchTop = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: margin)
let labelSide = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: sideMargin)
let labelCenter = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: sw, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
self.addConstraint(switchSide)
self.addConstraint(switchTop)
self.addConstraint(labelSide)
self.addConstraint(labelCenter)
let left = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: sideMargin)
let right = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: -sideMargin)
let top = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: sw, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: margin)
let bottom = NSLayoutConstraint(item: longLabel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -margin)
self.addConstraint(left)
self.addConstraint(right)
self.addConstraint(top)
self.addConstraint(bottom)
self.cellConstraints += [switchSide, switchTop, labelSide, labelCenter, left, right, top, bottom]
self.constraintsSetForLongLabel = true
}
else {
let switchSide = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: -sideMargin)
let switchTop = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: margin)
let switchBottom = NSLayoutConstraint(item: sw, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -margin)
let labelSide = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: sideMargin)
let labelCenter = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: sw, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
self.addConstraint(switchSide)
self.addConstraint(switchTop)
self.addConstraint(switchBottom)
self.addConstraint(labelSide)
self.addConstraint(labelCenter)
self.cellConstraints += [switchSide, switchTop, switchBottom, labelSide, labelCenter]
self.constraintsSetForLongLabel = false
}
}
// XXX: not in updateConstraints because it doesn't play nice with UITableViewAutomaticDimension for some reason
func changeConstraints() {
let hasLongText = self.longLabel.text != nil && !self.longLabel.text.isEmpty
if hasLongText != self.constraintsSetForLongLabel {
self.removeConstraints(self.cellConstraints)
self.cellConstraints.removeAll()
self.addConstraints()
}
}
}
You need to change many things into your project as per your requirement like you can use that setting view by hiding that tableView and add one UIView on it after that you can add emojis into that view and when user click on setting button from keyboard you can hide your emojis view and show tableview but when user want to type smiles that you don't need to hide anything just show your emojis view.
HERE is your updated project.

Resources