UIButton changing frame when constraint added - swift

I have a circular UIButton inside a UITableViewCell that I'm creating programmatically. It works fine, until I add a constraint to center it in it's superview.
This is what my button looks like before I add the constraint to it:
And this is what it looks like after I add the constraint:
Here's my code:
var thumbnailBtn = UIButton.buttonWithType(.Custom) as! UIButton
func setupViews() {
backgroundColor = .colorFromCode(0x3f3f3f)
thumbnailBtn.frame = CGRectMake(0, 0, 80, 80)
thumbnailBtn.layer.cornerRadius = 0.5 * thumbnailBtn.bounds.size.width
thumbnailBtn.backgroundColor = UIColor.greenColor()
thumbnailBtn.setTitle("Test", forState: UIControlState.Normal)
thumbnailBtn.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
contentView.addSubview(menuControlContainerView)
menuControlContainerView.addSubview(thumbnailBtn)
updateConstraints()
}
override func updateConstraints() {
if !didSetupConstraints {
UIView.autoSetPriority(1000) {
self.menuControlContainerView.autoSetContentCompressionResistancePriorityForAxis(.Vertical)
}
menuControlContainerView.autoPinEdgeToSuperviewEdge(.Top, withInset: 0)
menuControlContainerView.autoPinEdgeToSuperviewEdge(.Leading, withInset: 0)
menuControlContainerView.autoPinEdgeToSuperviewEdge(.Trailing, withInset: 0)
menuControlContainerView.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 0)
thumbnailBtn.autoCenterInSuperview()
didSetupConstraints = true
}
super.updateConstraints()
}
I noticed if I add this line of code [ thumbnailBtn.autoSetDimensionsToSize(CGSizeMake(80, 80)) ] to updateConstraints() it works and looks like this:
But is this the cleanest way to do this since I'm setting the size twice?
Any help will greatly be appreciated. Thanks.

You set the size in the initial frame but that is inappropriate when you later start using constraints to specify the position (and the superview layout). Really you should just create a plain view (using the appropriate method from the 3rd party library you're using) and then specify the size and position using constraints (the ones you've already tried are appropriate).
The view is most likely resized when you centre it because the 3rd party library removes the auto-resizing mask conversion to constraints, this allows the constraint engine to basically do whatever it wants as any settings satisfy the equations.

Related

Prevent cell content from "jumping" when applying constraint

I have a subclassed UICollectionViewCell and I want it to expand when tapped.
To achieve this, I put the title into a view ("titleStack") and the body into a separate view ("bodyStack"), and then put both of them into a container UIStackView ("mainStack"). I then constrain the contentView of the cell to the leading, trailing, and top edges of mainStack.
When the cell is selected, a constraint is applied that sets the bottom of the contentView's constraint to be the bottom of bodyStack. When it's unselected, I remove that constraint and instead apply one that sets the contentView's bottom constraint equal to titleStack's bottom constraint.
For the most part this works well, but when deselecting, there's this little jump, as you can see in this video:
What I would like is for titleStack to stay pinned to the top while the cell animates the shrinking portion, but it appears to jump to the bottom, giving it a sort of glitchy look. I'm wondering how I can change this.
I've pasted the relevant code below:
private func setUp() {
backgroundColor = .systemGray6
clipsToBounds = true
layer.cornerRadius = cornerRadius
setUpMainStack()
setUpConstraints()
updateAppearance()
}
private func setUpMainStack() {
contentView.constrain(mainStack, using: .edges, padding: 5, except: [.bottom])
mainStack.add([titleStack, bodyStack])
bodyStack.add([countryLabel, foundedLabel, codeLabel, nationalLabel])
}
private func setUpConstraints() {
titleStack.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
closedConstraint =
titleStack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
closedConstraint?.priority = .defaultLow // use low priority so stack stays pinned to top of cell
openConstraint =
bodyStack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
openConstraint?.priority = .defaultLow
}
/// Updates the views to reflect changes in selection
private func updateAppearance() {
UIView.animate(withDuration: 0.3) {
self.closedConstraint?.isActive = !self.isSelected
self.openConstraint?.isActive = self.isSelected
}
}
Thanks so much!
I was able to solve this by simply showing and hiding my "bodyStack" as well as using "layoutIfNeeded." I removed closedConstraint and openConstraint and just gave it a normal bottom constraint.
The relevant code:
func updateAppearance() {
UIView.animate(withDuration: 0.3) {
self.bodyStack.isHidden = !self.isSelected
self.layoutIfNeeded()
}
}

How to add red dot badge in table view cell?

Try to add red dot badge for every unread data in inbox tableviewcell.
I try using cell.accessoryview to add badge
let size: CGFloat = 9
let width = max(size, 0.7 * size * 1) // perfect circle is smallest allowed
let badge = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: size))
badge.layer.cornerRadius = size / 2
badge.layer.masksToBounds = true
badge.textAlignment = .center
badge.textColor = UIColor.white
badge.backgroundColor = UIColor.red
if viewModel.sortedInboxItems[indexPath.section].isRead {
cell.accessoryView = badge
}
But if using cell.accessoryview it will change the display like image below (TIME in the right corner of the cell is moving forward). How to make it not change the display?
EDIT
Try to create dot as uilabel in custom uitableview cell like image below
But the result show like this image below. The red dot shape is not good enough? Can someone help with this issue ?
The accessoryView is not part of the contentView of the cell. If you set the accessoryView it will push the contentView over to make room for itself. More information on that can be found here; this diagram is helpful:
If you don't want it to do this, put your red dot into the cell itself instead of using the accessoryView. It's unclear how you've built your cells, but it looks like you've created a custom UITableViewCell, so you should be able to do this without trouble.
Or as commented above, you could include your time label in your accessory view alongside the red dot if applicable.
Consider using a UIView with corner radius just like you did with the label. To make sure that the shape is right (sizes have initialised properly) change its corner radius in an overriden layoutSubviews.
override func layoutSubviews() {
super.layoutSubviews()
badgeInboxView.layer.cornerRadius = badgeInboxView.frame.height/2
}

UIButton Not Clickable when added UITabbar

When added UIButton on UITabbar to middle as shown in figure.
The button action on above the UITabBar unable to click
func setupMiddleButton() {
plusButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
var menuButtonFrame = plusButton.frame
menuButtonFrame.origin.x = tabBar.bounds.width/2 - menuButtonFrame.size.width/2
let hasNotched :Bool? = UIDevice.current.hasNotch
if hasNotched != nil {
menuButtonFrame.origin.y = tabBar.bounds.height - menuButtonFrame.height - 15
} else {
menuButtonFrame.origin.y = tabBar.bounds.height - menuButtonFrame.height - 50
}
plusButton.frame = menuButtonFrame
plusButton.setTitle("+", for: .normal)
plusButton.titleLabel?.font = UIFont.helveticaNeue(ofSize: 40)
plusButton.backgroundColor = UIColor.init(hexString: "5E71FE")
plusButton.titleEdgeInsets = UIEdgeInsets(top: 0,left: 10,bottom: 10,right: 10)
tabBar.addSubview(plusButton)
plusButton.layer.cornerRadius = menuButtonFrame.height/2
plusButton.addTarget(self, action: #selector(plusButtonAction(sender:)), for: .touchUpInside)
}
You need to override the hitTest method in your custom tab bar class like this
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView?
{
guard !clipsToBounds && !isHidden && alpha > 0 else { return nil }
for member in subviews.reversed()
{
let subPoint = member.convert(point, from: self)
guard let result = member.hitTest(subPoint, with: event)
else { continue }
return result
}
return nil
}
Basically the problem is that upper part is not clickable because it is outside of the bounds of main content view of tab bar.
This method will check if the tap is inside the bounds of the view, if it is it will return the view and the action for that button will get called.
Documentation by apple: Link
P.s I was facing the same issue recently and got this help which worked smooth.
I suspect that what you are trying to do is not possible, or at the least, not supported by Apple. (And thus not recommended since you might find a way to make it might work today but not in some future OS version.)
As a rule, Apple does not support you adding custom view objects to system components like tab bars, navigation bars, stack views, table/collection view controllers, etc except through a documented API.
I would suggest NOT doing what you are trying to do. instead, add a button in the content view of the tab bar controller. I don't know if you'll be able to make it partly cover the tab bar like you are trying to do however.
Add the button to the view of the UITabbarController instead of adding to the TabBar. And then reposition the button, it will work.

Apple iOS Tutorial: Problems getting UIButton addTarget to Work

I am working through the "Start Developing iOS Apps" tutorial provided by Apple, and having a problem in the Implement a Custom Control section. I have tried everything to get the button to print something to the console, but can't get it to work. I am on the section in the tutorial "Add Buttons to the View" about a fifth of the way down the page.
Everything else works fine.
I have set up the RatingControl.swift file as follows:
import UIKit
class RatingControl: UIView {
// MARK: Initialisation
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Create a square button
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
// Set the background colour of the button
button.backgroundColor = UIColor.darkGray
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), for: .touchDown)
// Add the button to the view
addSubview(button)
}
// MARK: Button Action
func ratingButtonTapped(_: UIButton) {
print("Button pressed")
}
}
A few things there are slightly different to the tutorial, but that is because Xcode says things have changed.
In my Main.storyboard file I have added a View using the RatingControl class. The button displays but nothing happens when I click it.
Any help would be appreciated. If any extra information is needed please let me know.
There is actually a hierarchy of three views in this story:
A stack view (not mentioned in the original question)
The RatingControl
The button
Well, the stack view, a complicated control whose job involves a lot of voodoo with the constraints of its arranged subviews, is reducing the size of the RatingControl to zero. The button is thus outside the RatingControl's bounds (easily proved by giving the RatingControl a background color — the background color doesn't appear). The RatingControl does not clip to its bounds, so the button is still visible — but, being outside its superview, it is not tappable.
As for why the stack view is reducing the size of the RatingControl to zero: it's because the RatingControl has no intrisicContentSize. The reason why we need this is complicated and has to do with how a stack view manipulates its arranged subviews and gives them constraints. But in essence, it makes a lot of its decisions based on an arranged view's intrinsicContentSize.
In the comments you said:
In size inspector it has intrinsic size set to placeholder, width 240, height 44. Or is there something I need to do to stop the stack view making it zero sized?
The key thing to understand here is that that setting in the size inspector is only a placeholder. It is merely to shut the storyboard up so that it won't complain. It doesn't actually give the view any intrinsic size at runtime. To do that, you must actually override the intrinsicContentSize property, in your code, as a computed variable returning an actual size.
Looks like you're stumbling through the "Start Developing iOS Apps (Swift)" tutorial before it's updated for iOS 10 and Swift 3. Amazing you've made it this far! Anyhow, #matt has a great technical explanation below but did not include the actual code to get your tutorial working:
Add the following to your class definition (outside the init function):
override var intrinsicContentSize: CGSize {
return CGSize(width: 240, height: 44)
}
then your code will work : -
class RatingView: UIView {
// MARK: Initialisation
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Create a square button
let button = UIButton(frame: CGRect(x: 200, y: 100, width: 44, height: 44))
// Set the background colour of the button
button.backgroundColor = UIColor.darkGray
button.addTarget(self, action: #selector(self.ratingButtonTapped(_:)), for: .touchDown)
// Add the button to the view
addSubview(button)
}
// MARK: Button Action
func ratingButtonTapped(_: UIButton) {
print("Button pressed")
}
}

Add view over tableview (UITableViewController)

Situation: I've got a UITableViewController loading some data asynchronously from a service. During this time I would like to place a full screen (except navigation bar) view over the table view showing my custom indicator and text.
Problem: The problem I'm facing is that when my custom view (it has a red background) is placed over the UITableView the lines of the table view are shown trough my custom view (see image below).
What I tried:
I tried to use insertBelow and above, didn't work. I also tried to do: tableview.Hidden = true, but this also hides the custom view for some reason as seen on image 2.
Image1: For some reason I can see the lines threw my view.
Image 2: Tableview + custom view gone when hidden = true used.
My code:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
UIView view = new UIView (new RectangleF (0, 0, this.TableView.Frame.Width, this.TableView.Frame.Height));
view.BackgroundColor = UIColor.Red;
this.TableView.AddSubview (view);
TableView.Source = new SessionTableViewSource ();
}
You can use self.navigationController.view as view for adding subview.
The issue is that the View of a UITableViewController is a UITableView, so you cannot add subviews to the controller on top of the table.
I'd recommend switching from a UITableViewController to a simple UIViewController that contains a UITableView. This way the controller main view is a plain UIView that contains a table, and you can add subviews to the main UIView and they will be placed on top of the table view.
You can try to add the view to the window instead of nesting it in the table view like this:
UIWindow* mainWindow = [[UIApplication sharedApplication] keyWindow];
[mainWindow addSubview: overlayview];
UIWindow* window = [[UIApplication sharedApplication].delegate.window;
[window addSubview: your-overlayview];
Swift / Storyboard Solution
Note: The code below assumes one has a custom view (ratingView in my case) that is to be presented over a UITableView.
I've read many answers to this and similar questions on SO. The other answers from these sources worked to varying degrees for me (e.g.,view loaded but not shown or not accessible,...). I am using Swift 2.0+ and I am sharing the complete solution for doing this using a UITableViewController.
Create an outlet to the Navigation Bar and the view, which you want to bring over the tableview.
//MARK:Outlets
#IBOutlet weak var navBar:UINavigationBar!
#IBOutlet var ratingView: MNGStarRating!
In my case I also wanted to animate the view over the tableview so I used a class variable to hold a reference to the inflection point and a point above the scene (off-screen).
var centerYInflection:NSLayoutConstraint!
var aPointAboveScene = -(max(UIScreen.mainScreen().bounds.width,UIScreen.mainScreen().bounds.height) * 2.0)
Then in viewDidLoad I called a function (configureRatingViewAutoLayout) which configures and adds the constraints for the new view to be animated over the tableview.
func configureRatingViewAutoLayout() {
//REQUIRED
self.navBar.superview?.addSubview(self.ratingView)
var newConstraints:[NSLayoutConstraint] = []
newConstraints.append(self.ratingView.leadingAnchor.constraintEqualToAnchor(self.view.leadingAnchor,constant: 10))
newConstraints.append(self.ratingView.trailingAnchor.constraintEqualToAnchor(self.view.trailingAnchor,constant: 10))
newConstraints.append(self.ratingView.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor))
//hides the rating view above the scene
self.centerYInflection = self.ratingView.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor, constant: self.aPointAboveScene)
//the priority must be set below 1000 if you intend to change it after it has been added to a view
self.centerYInflection.priority = 750
newConstraints.append(self.centerYInflection)
//constraints must be added to the container view of the two items
self.ratingView.superview?.addConstraints(newConstraints)
}
Nota Bene - On a UITableViewController; the self.view is the
self.tableView. They point to the same thing so I guess one could also
use the self.tableView reference above.
Sometime later... In response to a UIControl event I call this method.
#IBAction func toggleRatingView (sender:AnyObject?){
//REQUIRED
self.ratingView.superview?.layoutIfNeeded()
UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.37, initialSpringVelocity: 0.99, options: [.CurveEaseOut], animations: { () -> Void in
if CGRectContainsRect(self.view.frame, self.ratingView.frame) {
//in frame ~ animate away
//I play a sound to alert the user something is happening
self.centerYInflection.constant = self.aPointAboveScene
self.centerYInflection.priority = UILayoutPriority(950)
//I disable portions of the UI
self.disableUIElements(nil)
} else {
//out of frame ~ animate in
//I play a different sound here
self.centerYInflection.constant = 0
self.centerYInflection.priority = UILayoutPriority(950)
//I enable the UI fully
self.enableUIElements(nil)
}
//REQUIRED
self.ratingView.superview?.setNeedsLayout()
self.ratingView.superview?.layoutIfNeeded()
}) { (success) -> Void in
//do something else
}
}
These helper methods can be configured to control access to elements in your scene during the presentation of the view.
func disableUIElements(sender:AnyObject?) {
//UI
}
func enableUIElements(sender:AnyObject?) {
//UI
}
Caveats
My view is a custom view in the Storyboard (sitting outside of the
tableview but connected to the TableView Controller). The view has a
required user runtime attribute defined layer.zPosition with a Number value set to 2 (this ensures that it presents in front of the
UITableView).
One could also try playing around with bringSubviewToFront:
and sendSubviewToBack: methods if you don't want to set the zPosition
(I think zPosition is simpler to use)
Try this to hook a button at bottom of the UITableViewController
declare button as a variable:
var submitButton: UIButton!
and in viewDidLoad:
submitButton = UIButton(frame: CGRect(x: 5, y: UIScreen.main.bounds.size.height - 50, width: UIScreen.main.bounds.size.width - 10, height: 50))
submitButton.backgroundColor = UIColor.init(red: 180/255, green: 40/255, blue: 56/255, alpha: 1.0)
submitButton.setTitle("Submit", for: .normal)
submitButton.titleLabel?.font = UIFont(name: "Arial", size: 15)
submitButton.titleLabel?.textColor = .white
submitButton.addTarget(self, action: #selector(submit), for: .touchUpInside)
submitButton.layer.cornerRadius = 5
self.view.addSubview(submitButton)
and implement this method:
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
submitButton.frame = CGRect.init(x: submitButton.frame.origin.x, y: UIScreen.main.bounds.size.height + scrollView.contentOffset.y - 50, width: submitButton.frame.width, height: submitButton.frame.height)
}
This works for me:
if let myTopView = Bundle.main.loadNibNamed("MyTopView", owner: self, options: nil)?.first as? MyTopView {
if let view = UIApplication.shared.keyWindow{
view.addSubview(myView);
myTopView.translatesAutoresizingMaskIntoConstraints = false
myTopView.topAnchor.constraint(equalTo: view.topAnchor ).isActive = true
myTopView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
myTopView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
myTopView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}