How do I iterate over all controls in a View - cocoa-touch

I have a static table view controller. Within some of the cells, I have text boxes. I would like to enable or disable all the text boxes in one go. I know I could do something like
self.nameTextField.Enabled = NO;
self.ageTextField.Enabled = NO;
self.hairColorTextField.Enabled = NO;
But there has to be something more elegant. Something like
for (UIControl* control in self.allChildControls) { // <-- I totally just made that up.
if ([control isKindOfClass:[UITextField class]]) {
control.Enabled = NO;
}
}
I don't think I am asking the right question...

You can use the subviews property od UIView. It contains all child UI elements.
#property(nonatomic, readonly, copy) NSArray *subviews
UIView Documentation
for (UIView *subview in self.view.subviews) {
//check by class or tag
}

If you have a static tableviewController, I am assuming you aren't allowing the user to add/delete cells. If this is the case, your question is simple. You just need to add an outlet to each of the UITextField objects and toggle it's userInteractionEnabled property to no.
self.myTextField.userInteractionEnabled = NO;
self.mySecondTextField.userInteractionEnabled = NO;
Hope this helps :)

Related

Change MKAnnotationView programmatically

Is there a way to change MKAnnotationView style (like from red label with number to green colored label with number).
I want to change this style according to distance from target. My annotation is moving, with user.
I dont want to use remove / add annotation, because it causes "blinking".
Can it be done someway?
UPDATE:
I am adding code, how I am doing it right now
MKAnnotationView *av = [mapView viewForAnnotation:an];
if ([data->type isMemberOfClass:[UserAnnotationImage class]])
{
UIImage *img = [UIImage imageNamed: ((UserAnnotationImage *)data->type)->url];
[av setImage:img];
}
else if ([data->type isMemberOfClass:[UserAnnotationLabel class]])
{
UIView * v = [av viewWithTag:0];
v = ((UserAnnotationLabel *)data->type)->lbl;
av.frame = ((UserAnnotationLabel *)data->type)->lbl.frame;
}
else if ([data->type isMemberOfClass:[UserAnnotationView class]])
{
UIView * v = [av viewWithTag:0];
v = ((UserAnnotationView *)data->type)->view;
av.frame = ((UserAnnotationView *)data->type)->view.frame;
}
Sadly, its not working :(
Yes, basically you get a reference to the annotation view and update its contents directly.
Another way, if you have a custom annotation view class, is to have the annotation view monitor the changes it is interested in (or have something outside tell it) and update itself.
The first approach is simpler if you are using a plain MKAnnotationView or MKPinAnnotationView.
Wherever you detect that a change to the view is needed, get a reference to the view by calling the map view's viewForAnnotation instance method. This is not the same as calling the viewForAnnotation delegate method.
Once you have a reference to the view, you can modify as needed and the changes should appear immediately.
An important point is that the logic you use to update the view outside the delegate method and the logic you have in the viewForAnnotation delegate method must match. This is because the delegate method may get called later (after you've updated the view manually) by the map view and when it does, the code there should take the updated data into account.
The best way to do that is to have the annotation view construction code in a common method called both by the delegate method and where you update the view manually.
See change UIImage from MKAnnotation in the MKMapView for an example that updates just the annotation view's image.
For an example (mostly an idea for an approach) of updating the view using a custom annotation view class, see iPad Mapkit - Change title of "Current Location" which updates the view's pin color periodically (green, purple, red, green, purple, red, etc).
There are too many unknowns in your code to explain why it doesn't work. For example:
What is data? Is it annotation-specific (is it related to an)? What is type? Does it change after the annotation has been added to the map?
Why is data storing entire view objects like a UILabel or UIView instead of just the underlying data that you want to show in those views?
imageNamed requires the image to be a resource in the project (not any arbitrary url)
Don't use a tag of 0 (that's the default for all views). Start numbering from 1.
You get a view using viewWithTag but then replace it immediately with another view.
I'll instead give a more detailed but simple(r) example...
Assume you have an annotation class (the one that implements MKAnnotation) with these properties (in addition to coordinate, title, and subtitle):
#property (nonatomic, assign) BOOL haveImage;
#property (nonatomic, copy) NSString *labelText;
#property (nonatomic, copy) NSString *imageName;
#property (nonatomic, assign) CLLocationDistance distanceFromTarget;
To address the "important point" mentioned above (that the viewForAnnotation delegate method and the view-update-code should use the same logic), we'll create a method that is passed an annotation view and configures it as needed based on the annotation's properties. This method will then be called both by the viewForAnnotation delegate method and the code that manually updates the view when the annotation's properties change.
In this example, I made it so that the annotation view shows the image if haveImage is YES otherwise it shows the label. Additionally, the label's background color is based on distanceFromTarget:
-(void)configureAnnotationView:(MKAnnotationView *)av
{
MyAnnotationClass *myAnn = (MyAnnotationClass *)av.annotation;
UILabel *labelView = (UILabel *)[av viewWithTag:1];
if (myAnn.haveImage)
{
//show image and remove label...
av.image = [UIImage imageNamed:myAnn.imageName];
[labelView removeFromSuperview];
}
else
{
//remove image and show label...
av.image = nil;
if (labelView == nil)
{
//create and add label...
labelView = [[[UILabel alloc]
initWithFrame:CGRectMake(0, 0, 50, 30)] autorelease];
labelView.tag = 1;
labelView.textColor = [UIColor whiteColor];
[av addSubview:labelView];
}
if (myAnn.distanceFromTarget > 100)
labelView.backgroundColor = [UIColor redColor];
else
labelView.backgroundColor = [UIColor greenColor];
labelView.text = myAnn.labelText;
}
}
The viewForAnnotation delegate method would look like this:
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MyAnnotationClass class]])
{
static NSString *myAnnId = #"myann";
MKAnnotationView *av = [mapView dequeueReusableAnnotationViewWithIdentifier:myAnnId];
if (av == nil)
{
av = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:myAnnId] autorelease];
}
else
{
av.annotation = annotation;
}
[self configureAnnotationView:av];
return av;
}
return nil;
}
Finally, the place where the annotation's properties change and where you want to update the annotation view, the code would look something like this:
ann.coordinate = someNewCoordinate;
ann.distanceFromTarget = theDistanceFromTarget;
ann.labelText = someNewText;
ann.haveImage = YES or NO;
ann.imageName = someImageName;
MKAnnotationView *av = [mapView viewForAnnotation:ann];
[self configureAnnotationView:av];

Get the object at top of uiview hierarchy

I have a known location (CGPoint) and I want to query the view (UIView) for the object under it or that contains it, whether its the view itself, or a button inside that, or a label or any other instance
I then want to grab that object, find out it type, and call any methods that happen when its tapped by the user.
I tried calling touchesBegan on the view, but theres no way to create touch events or uievents it seems... correct me if I'm wrong.
I'm thinking there might be a way to do this with hitTest, but I'm unsure.
hit test will do it.
If you don't want something returned, turn off userInteractionEnabled
//Send touch down event
//Now, this is a bit hacky. Theres no public contrustors for UITouch or UIEvent, thus calling touches*: on the view is not possible. Instead, I search the view underneath it (with Hit Test) and call actions on that.
//Note. You need to allow for each type of object below, for the scope of the demo, I've allowed for only UIView and UIButton.
UIView *v = [[self view] hitTest:pointer.frame.origin withEvent:nil]; //origin is top left, point of pointer.
NSLog(#"%#", [v class] );
if([v isKindOfClass:[UIButton class]]){
selectedButton = (UIButton *)v;
}
else if ([v isKindOfClass:[UIView class]] && [[v backgroundColor] isEqual:[UIColor redColor]]){
selectedView = v;
dragLabel.text = #"You are dragging me!";
dragPoint = pointer.frame.origin; //record this point for later.
}
else {
NSLog (#"touched but no button underneath it");
}

hide or show tableview

Say I have a switch and a small table view(no scroll) below it. I know if the switch is turned on/off using a bool switchState whose value get changed in the action method of the switch:
-(IBAction)switchSlide:(id)sender{
if (toggleSwitch.on == YES) {
switchState = YES;
}
else{
switchState = NO;
}
}
Now what I want is that the table view below it should hide when the switchState == NO. How do I do that?
Every UIView has a property hidden:
#property(nonatomic, getter=isHidden) BOOL hidden
since a UITableView is a sublass of UIView you can use the methods from a UIView too.
So your code just need a little adjustment (assuming you are calling this IBAction in a UITableViewController):
-(IBAction)switchSlide:(id)sender{
if (toggleSwitch.on == YES) {
switchState = YES;
self.tableView.hidden = NO;
}
else{
switchState = NO;
self.tableView.hidden = YES;
}
}
Edit:
Solved this via chat and the solution is:
Since you used a UIViewController you have to make a propert for the UITableView. synthesize it and connect the outlet by dragging from the files owner to the UITableView in the interface builder. Now you can use the code above.

Equivalent to a "ListBox" in XCode?

You know Visual Studio, that awesome element called "ListBox"? Just a box that would list a bunch of strings.
I am now working with XCode, and I found this class in the interface builder "NSScrollView". It seems to be able to list me a couple strings. It says it got a NSTextView inside, but, how do I access it?
I am not even sure if NSScrollView is the correct solution I need, but if I could simply access the NSTextView inside it, I think it would be enough.
See NSTableView.
As for getting to a text view inside a scroll view, create an Interface Builder outlet (IBOutlet) and connect it to the text view itself, rather than the scroll view.
To get to a text view inside a scroll view; you need to select the controller with your outlet defined; click and hold control and then drag the blue connection line from your controller to the top line of the scroll view; then just wait for a blue line to appear; this will then prompt to let you link your outlet to the text view.
Josh's answer above to use NSTableView is correct. For those not that familiar with it, it can seem like a much bigger task than it actually turns out to be. Hopefully this saves people some time.
Rather than fight with NSTableCellView assumptions, you can create any type of simple view you want and use auto layout (or even return a simple NSTextView. This is what I did to get more control over layout of my text strings:
#interface PreferenceTableViewCell : NSView
#property (nonnull, strong, readonly) NSTextField *tf;
#end
#implementation PreferenceTableViewCell
-(id)init
{
self = [super init];
if(self) {
self.translatesAutoresizingMaskIntoConstraints = NO;
self.autoresizesSubviews = YES;
_tf = [NSTextField labelWithString:#""];
_ tf.translatesAutoresizingMaskIntoConstraints = NO;
_tf.autoresizesSubviews = YES;
[self addSubview:_tf];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-(10)-[_tf]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_tf)]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:_tf attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
}
return self;
}
#end
Then put this whereever you need the list of strings (or controls, or whatever):
_tv = [NSTableView new];
_tv.translatesAutoresizingMaskIntoConstraints = NO;
_tv.autoresizesSubviews = YES;
_tv.focusRingType = NSFocusRingTypeNone;
_tv.delegate = self;
_tv.dataSource = self;
_tv.rowHeight = 40; // Use this to adjust the height of your cell or do it in cell.
_tv.headerView = nil;
_tv.selectionHighlightStyle = NSTableViewSelectionHighlightStyleRegular;
_tv.allowsColumnReordering = NO;
_tv.allowsColumnResizing = NO;
_tv.allowsEmptySelection = NO;
_tv.allowsTypeSelect = NO;
_tv.gridStyleMask = NSTableViewGridNone;
[panel addSubview:_tv];
// TableView Column
NSTableColumn *col1 = [[NSTableColumn alloc] initWithIdentifier:#"c1"];
col1.resizingMask = NSTableColumnAutoresizingMask;
[_tv addTableColumn:col1];
Then in whatever is set as the delegate and datasource for the NSTableView add these methods:
-(NSInteger)numberOfRowsInTableView:(NSTableView *)tv
{
return stringArray.count;
}
-(NSView *)tableView:(NSTableView *)tv viewForTableColumn:(NSTableColumn *)tc row:(NSInteger)row
{
// This can be ANY NSView based control built as shown above.
PreferenceTableViewCell *cell = [PreferenceTableViewCell new];
cell.tf.stringValue = stringArray[row];
return cell;
}
-(void)tableViewSelectionDidChange:(NSNotification *)notification
{
// Code to do whatever when a list item is selected.
}
That is basically it for a simple list. See the Apple Docs on NSTableView for more details on how to bind the table to a data sources and more complicated problems.

Selection Highlight in NSCollectionView

I have a working NSCollectionView with one minor, but critical, exception. Getting and highlighting the selected item within the collection.
I've had all this working prior to Snow Leopard, but something appears to have changed and I can't quite place my finger on it, so I took my NSCollectionView right back to a basic test and followed Apple's documentation for creating an NSCollectionView here:
http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/CollectionViews/Introduction/Introduction.html
The collection view works fine following the quick start guide. However, this guide doesn't discuss selection other than "There are such features as incorporating image views, setting objects as selectable or not selectable and changing colors if they are selected".
Using this as an example I went to the next step of binding the Array Controller to the NSCollectionView with the controller key selectionIndexes, thinking that this would bind any selection I make between the NSCollectionView and the array controller and thus firing off a KVO notification. I also set the NSCollectionView to be selectable in IB.
There appears to be no selection delegate for NSCollectionView and unlike most Cocoa UI views, there appears to be no default selected highlight.
So my problem really comes down to a related issue, but two distinct questions.
How do I capture a selection of an item?
How do I show a highlight of an item?
NSCollectionView's programming guides seem to be few and far between and most searches via Google appear to pull up pre-Snow Leopard implementations, or use the view in a separate XIB file.
For the latter (separate XIB file for the view), I don't see why this should be a pre-requisite otherwise I would have suspected that Apple would not have included the view in the same bundle as the collection view item.
I know this is going to be a "can't see the wood for the trees" issue - so I'm prepared for the "doh!" moment.
As usual, any and all help much appreciated.
Update 1
OK, so I figured finding the selected item(s), but have yet to figure the highlighting. For the interested on figuring the selected items (assuming you are following the Apple guide):
In the controller (in my test case the App Delegate) I added the following:
In awakeFromNib
[personArrayController addObserver:self
forKeyPath:#"selectionIndexes"
options:NSKeyValueObservingOptionNew
context:nil];
New Method
-(void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if([keyPath isEqualTo:#"selectionIndexes"])
{
if([[personArrayController selectedObjects] count] > 0)
{
if ([[personArrayController selectedObjects] count] == 1)
{
personModel * pm = (PersonModel *)
[[personArrayController selectedObjects] objectAtIndex:0];
NSLog(#"Only 1 selected: %#", [pm name]);
}
else
{
// More than one selected - iterate if need be
}
}
}
Don't forget to dealloc for non-GC
-(void)dealloc
{
[personArrayController removeObserver:self
forKeyPath:#"selectionIndexes"];
[super dealloc];
}
Still searching for the highlight resolution...
Update 2
Took Macatomy's advice but still had an issue. Posting the relevant class methods to see where I've gone wrong.
MyView.h
#import <Cocoa/Cocoa.h>
#interface MyView : NSView {
BOOL selected;
}
#property (readwrite) BOOL selected;
#end
MyView.m
#import "MyView.h"
#implementation MyView
#synthesize selected;
-(id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
-(void)drawRect:(NSRect)dirtyRect
{
NSRect outerFrame = NSMakeRect(0, 0, 143, 104);
NSRect selectedFrame = NSInsetRect(outerFrame, 2, 2);
if (selected)
[[NSColor yellowColor] set];
else
[[NSColor redColor] set];
[NSBezierPath strokeRect:selectedFrame];
}
#end
MyCollectionViewItem.h
#import <Cocoa/Cocoa.h>
#class MyView;
#interface MyCollectionViewItem : NSCollectionViewItem {
}
#end
"MyCollectionViewItem.m*
#import "MyCollectionViewItem.h"
#import "MyView.h"
#implementation MyCollectionViewItem
-(void)setSelected:(BOOL)flag
{
[(MyView *)[self view] setSelected:flag];
[(MyView *)[self view] setNeedsDisplay:YES];
}
#end
If a different background color will suffice as a highlight, you could simply use an NSBox as the root item for you collection item view.
Fill the NSBox with the highlight color of your choice.
Set the NSBox to Custom so the fill will work.
Set the NSBox to transparent.
Bind the transparency attribute of the NSBox to the selected attribute of File Owner(Collection Item)
Set the value transformer for the transparent binding to NSNegateBoolean.
I tried to attach Interface builder screenshots but I was rejected bcos I'm a newbie :-(
Its not too hard to do. Make sure "Selection" is enabled for the NSCollectionView in Interface Builder. Then in the NSView subclass that you are using for your prototype view, declare a property called "selected" :
#property (readwrite) BOOL selected;
UPDATED CODE HERE: (added super call)
Subclass NSCollectionViewItem and override -setSelected:
- (void)setSelected:(BOOL)flag
{
[super setSelected:flag];
[(PrototypeView*)[self view] setSelected:flag];
[(PrototypeView*)[self view] setNeedsDisplay:YES];
}
Then you need to add code in your prototype view's drawRect: method to draw the highlight:
- (void)drawRect:(NSRect)dirtyRect
{
if (selected) {
[[NSColor blueColor] set];
NSRectFill([self bounds]);
}
}
That just simply fills the view in blue when its selected, but that can be customized to draw the highlight any way you want. I've used this in my own apps and it works great.
You can also go another way, if you're not subclassing NSView for your protoype view.
In your subclassed NSCollectionViewItem override setSelected:
- (void)setSelected:(BOOL)selected
{
[super setSelected:selected];
if (selected)
self.view.layer.backgroundColor = [NSColor redColor].CGColor;
else
self.view.layer.backgroundColor = [NSColor clearColor].CGColor;
}
And of course, as said by all the wise people before me, make sure "Selection" is enabled for the NSCollectionView in Interface Builder.
In your NSCollectionViewItem subclass, override isSelected and change background color of the layer. Test in macOS 10.14 and Swift 4.2
class Cell: NSCollectionViewItem {
override func loadView() {
self.view = NSView()
self.view.wantsLayer = true
}
override var isSelected: Bool {
didSet {
self.view.layer?.backgroundColor = isSelected ? NSColor.gray.cgColor : NSColor.clear.cgColor
}
}
}
Since none of the existing answers worked super well for me, here is my take on it. Change the subclass of the CollectionView item to SelectableCollectionViewItem. Here is it's code. Comes with a bindable textColor property for hooking your text label textColor binding to.
#implementation SelectableCollectionViewItem
+ (NSSet *)keyPathsForValuesAffectingTextColor
{
return [NSSet setWithObjects:#"selected", nil];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.wantsLayer = YES;
}
- (void) viewDidAppear
{
// seems the inital selection state is not done by Apple in a KVO compliant manner, update background color manually
[self updateBackgroundColorForSelectionState:self.isSelected];
}
- (void)updateBackgroundColorForSelectionState:(BOOL)flag
{
if (flag)
{
self.view.layer.backgroundColor = [[NSColor alternateSelectedControlColor] CGColor];
}
else
{
self.view.layer.backgroundColor = [[NSColor clearColor] CGColor];
}
}
- (void)setSelected:(BOOL)flag
{
[super setSelected:flag];
[self updateBackgroundColorForSelectionState:flag];
}
- (NSColor*) textColor
{
return self.selected ? [NSColor whiteColor] : [NSColor textColor];
}
In my case I wanted an image(check mark) to indicate selection of object. Drag an ImageWell to the Collection Item nib. Set the desired image and mark it as hidden. Go to bindings inspector and bind hidden attribute to Collection View Item.
(In my case I had created a separate nib for CollectionViewItem, so its binded to File's owner. If this is not the case and Item view is in the same nib as the CollectionView then bind to Collection View Item)
Set model key path as selected and Value transformer to NSNegateBoolean. Thats it now whenever the individual cells/items are selected the image will be visible, hence indicating the selection.
Adding to Alter's answer.
To set NSBox as root item. Simply create a new IB document(say CollectionItem) and drag an NSBox to the empty area. Now add all the elements as required inside the box. Now click on File's Owner and set Custom Class as NSCollectionViewItem.
And in the nib where NSCollectionView is added change the nib name for CollectionViewItem
In the NSBox, bind the remaining elements to Files Owner. For a label it would be similar to :
Now to get the highlight color as Alter mentioned in his answer, set desired color combination in the Fill Color option, set the NSBox to transparent and bind the transparency attribute as below:
Now when Collection View Items are selected you should be able to see the fill color of the box.
This was awesome, thanks alot! i was struggling with this!
To clarify for to others:
[(PrototypeView*)[self view] setSelected:flag];
[(PrototypeView*)[self view] setNeedsDisplay:YES];
Replace PrototypeView* with the name of your prototype class name.
In case you are digging around for the updated Swift solution, see this response.
class MyViewItem: NSCollectionViewItem {
override var isSelected: Bool {
didSet {
self.view.layer?.backgroundColor = (isSelected ? NSColor.blue.cgColor : NSColor.clear.cgColor)
}
}
etc...
}
Here is the complete Swift NSCollectionViewItem with selection. Don't forget to set the NSCollectioView to selectable in IB or programmatically.
Tested under macOS Mojave (10.14) and High Sierra (10.13.6).
import Cocoa
class CollectionViewItem: NSCollectionViewItem {
private var selectionColor : CGColor {
let selectionColor : NSColor = (isSelected ? .alternateSelectedControlColor : .clear)
return selectionColor.cgColor
}
override var isSelected: Bool {
didSet {
super.isSelected = isSelected
updateSelection()
// Do other stuff if needed
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
updateSelection()
}
override func prepareForReuse() {
super.prepareForReuse()
updateSelection()
}
private func updateSelection() {
view.layer?.backgroundColor = self.selectionColor
}
}