IOS components in Swift Sliders, switches, segmented controls, pop-ups.
-
Upload
adela-gibson -
Category
Documents
-
view
226 -
download
0
Transcript of IOS components in Swift Sliders, switches, segmented controls, pop-ups.
iOS components in SwiftSliders, switches, segmented controls, pop-ups
Chap 4
Beginning iPhone Dev book
Create project
Single View
Add imagesGo to Images.xcassets in file inspector, click + in lower left corner, give it a name like ApressLogo
download the three Apress images, drag to 3 spaces.
second image should be 2x first image and third image should be 3x first image.
use for normal and retina displays
Create project
Go to storyboarddrag imageView to storyboard.
select it, go to Attributes editor, choose the ApressLogo image.
in View section, notice it says “Scale to Fill”. Scales the image.
With imageView selected, choose EditorSize to Fit Content. Now image and view are same size.
Now EditorAlignHorizontal Center in Container, then
Next fix constraints
Now notice all the attributes in the attribute editor. See pages 98-100 of the iPhone Dev book.
Labels and Text Fields
next add two labels and two text fields. Top label should be Name:
bottom label should be Number:
use the blue lines to make everything aligned.
Drag bottom field so that it’s width goes from the number: to the right margin (blue line)
make top field same width as bottom field.
make label text aligned right.
Then select both labels and EditorPinWidths Equally
Labels and Text Fields
For top text boxplaceholder: “Type in a name”
Change “return key” to “Done”
In View section, check the “opaque” (means that nothing behind this subview needs to be drawn) and uncheck the “Clears Graphics Context” and “Clip Subviews” (for efficiency sake)
Bottom text boxplaceholder: “Type in a number”
for “keyboard type” choose “number pad”
In View section, check the “opaque” (means that nothing behind this subview needs to be drawn) and uncheck the “Clears Graphics Context” and “Clip Subviews” (for efficiency sake)
Connecting
Create @IBOutlets for the two text fieldscall one nameField
call the other numberField
Closing the keyboardAdd following @IBAction method in viewController:
@IBAction func textFieldDoneEditing(sender: UITextField) {
sender.resignFirstResponder()
}
Go to storyboard. select Name field
go to connections inspector
drag from “Did End On Exit” to the yellow View Controller icon.
pop-up menu appears with name of IBAction we just created. Click it.
Repeat with other field.
Closing the keyboard IIneed to close when background is tapped
Add the @IBAction to viewController
@IBAction func backgroundTap(sender: UIControl) {
nameField.resignFirstResponder()
numberField.resignFirstResponder()
}
go to storyboardchoose the view
go to Identity Inspector on right panel
The field labeled Class says UIView. Change this to UIControlall controls that can trigger an IBAction are subclasses of UIControl
now open the Connections Inspector with the View still selected
Drag from circle by “Touch Down” to the View.
in the resulting dialog box choose the backgroundTap method
ControlsAnything you use on an interface
All controls are subclasses of UIControl
All can trigger action methodsThere are many different types of events
On event on a control can trigger many action methods
Can be visible or hidden
3 modesActive
Static (or inactive): no interaction possible (UIimage usually)
Passive Like UIImageView or UITextfield.
Hold a value until the program is ready to use it
Most are just containers of data; users don’t interact
Most controls can be used in all 3 modes
Control States
Every control has 4 possible control states. Is always in exactly one state:
Normal: default, not in any other state.
Highlighted: control is currently being used. Example: finger is on the button.
Disabled: control has been turned off (enable box unchecked in IB or enabled property to NO)
Selected: Usually used to indicate that a control is turned on. Similar to Highlighted, but the control can continue to be selected when the user is no longer directly using that control. Only used by some controls.
Control States
Certain controls can take on different attribute values depending on their state.
Example: different images for different states.
SlidersCreate a new “Single View” project
do not use storyboards
Create a sliderDrag slider from library
Size itLeft and right close to borders
Then choose EditorAlignHorizontal Center in Container
In attributes inspector setMinimum to 1
Maximum to 100
Current to 50
Leave update events, continuous checked
For the code for these slides, see the class web site, References->Examples->Components
Sliders
Add a label below the sliderChange text to 100
Choose Editor-Size to Fit Content
Now pin all components to the topSelect all components
Choose Editor-PinTop space to Superview
This will ensure that there is the same space no matter what orientation you have
Outlets
Shortcut for adding IBOutletsIn IB bring up the assistant editor
Control-drag from the slider to just above the @end declaration in the interface.
In the pop-up window chooseAction in the connection box
Type sliderChanged in the field
UISlider for the Type
hit return
Outlets
Now drag from the label to the interface (above the method you added).
Type sliderLabel into the Name text field
Hit return
Note the “weak” reference. This is a memory management reference. A pointer is kept to the object, but the object is not retained.
Implement the Action Method
Go to the viewController.m file
Note that the signature of the action method is there:
@IBAction func sliderChanged(sender: UISlider) {}
Fill in the body:
@IBAction func sliderChanged(sender: UISlider) {
let progress = lroundf(sender.value)
sliderLabel.text = "\(progress)"
}
Initialize the slider
Add to the viewDidLoad method:
− (void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
sliderLabel.text = "50”
;}
Run
Run the app
May have to go back to IB and pin the slider width
EditorPinWidth
Segmented Controls
Back to IBDrag a segmented control from the library to the interface.
Size to take up the width
Change names to Switches and Button
Switches
Add switchesDrag a switch from library to close to the left border
Option-drag the switch to create another one. Place it by the right border.
Create two outlets for the switches. Control-drag from the switches to the assistant editor
Name them leftSwitch and rightSwitch
Put in constraints on the switches
Switches
Create actions for the switchesturn on the assistant editor
Control-drag from the left switch to just below the @IBOutlets
Make it Action, with name switchChanged and type UISwitch
Hit return
Then control-drag from the right switch to the switchChanged method in the assistant editor.
We’ll use a single method to respond to both switches.
Segmented control action
Control-drag from the segmented control to the assistant editor, just above the @end
Insert a new action method called toggleControls
Set its sender parameter to UISegmentedControl
Implementing the action methods
Go to the viewController.m file
Add code:
−(IBAction)switchChanged:(UISwitch *)sender {
let setting = sender.on
leftSwitch.setOn(setting, animated: true)
rightSwitch.setOn(setting, animated: true)
}This sets both boxes. The sender parameter is a reference to the switch that was clicked. By clicking it, the button changed its state. We now change both buttons to that same state.
Add the button
Drag a rounded rectangle to the view and cover the switches completely.
Give it the name: Do Something
put in constraints
Add outlet/action
Add an outlet for the button called doSomethingButton
Add an action for the button called buttonPressed
when these are added, make the button hidden by clicking the checkbox in the attributes inspector in IB
Segmented Control Action
Add body to @IBAction func toggleControls method
@IBAction func toggleControls(sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { leftSwitch.hidden = false rightSwitch.hidden = false doSomethingButton.hidden = true } else { leftSwitch.hidden = true rightSwitch.hidden = true doSomethingButton.hidden = false }}
Background color
change background color of view to match the yellow in the image
go to storyboard
select main content view
choose attributes inspector
click the color swatch labeled background
click other open to OS X color picker
click on magnifying glass icon
click the Apress image
Action Sheets
Used to force the user to choose between two or more items.
It comes up from the bottom of the screen and displays a series of buttons.
Users cannot continue until they tap one of the buttons.
Alerts
Alerts appear as a rounded rectangle in the middle of the screen
User must respond to continue
Used to inform the user
Only have a single button (usually), but you can add more.
both action sheets and alerts are modal views
Action Sheet Part I let controller = UIAlertController(title: "Are You Sure?", message:nil, preferredStyle: .ActionSheet) let yesAction = UIAlertAction(title: "Yes, I'm sure!", style: .Destructive, handler: nil) let noAction = UIAlertAction(title: "No way!", style: .Cancel, handler: nil) controller.addAction(yesAction) controller.addAction(noAction) if let ppc = controller.popoverPresentationController { ppc.sourceView = sender ppc.sourceRect = sender.bounds } presentViewController(controller, animated: true, completion: nil)
Allocate and initialize a UIAlertController. This can display either an Action Sheet or an Alert
UIAlertController parameters:title to displaymessage to be displayed below the titlepreferredStyle is either ActionSheet or Alert
Add buttons to controller
Must create the buttons. If you only need 1, use an Alert
button parameters: title, style, handler to be called when button is pressed (or nil)Styles: UIAlertActionStyle.Destructive button triggers a destructive, dangerous action like deleting filesUIAlertActionStyle.Default normal use like an OK button.UIAlertActionStyle.Cancel used with a Cancel button.
Action Sheet Part II let controller = UIAlertController(title: "Are You Sure?", message:nil, preferredStyle: .ActionSheet) let yesAction = UIAlertAction(title: "Yes, I'm sure!", style: .Destructive, handler: nil) let noAction = UIAlertAction(title: "No way!", style: .Cancel, handler: nil) controller.addAction(yesAction) controller.addAction(noAction) if let ppc = controller.popoverPresentationController { ppc.sourceView = sender ppc.sourceRect = sender.bounds } presentViewController(controller, animated: true, completion: nil)
Allocate and initialize a UIAlertController. This can display either an Action Sheet or an Alert
Alert/Actionsheet always comes from bottom in iPhone, but from a control in iPad. A popover is only necessary in iPad. See pages 133-134 in the iPhone Dev book
causes the alert or actionsheet to be displayed on top of the current view
Alert Part IChange let yesAction = UIAlertAction(title: "Yes, I'm sure!", style: .Destructive, handler: nil) To let yesAction = UIAlertAction(title: "Yes, I'm sure!", style: .Destructive, handler: { action in let msg = self.nameField.text.isEmpty ? "You can breathe easy, everything went OK." : "You can breathe easy, \(self.nameField.text)," + " everything went OK." let controller2 = UIAlertController(title:"Something Was Done", message: msg, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Phew!", style: .Cancel, handler: nil) controller2.addAction(cancelAction) self.presentViewController(controller2, animated: true, completion: nil) })
handler: is the code that is executed when this button is clicked.
This is an if statement that puts a string in msg.
Alert Part IIChange let yesAction = UIAlertAction(title: "Yes, I'm sure!", style: .Destructive, handler: nil) To let yesAction = UIAlertAction(title: "Yes, I'm sure!", style: .Destructive, handler: { action in let msg = self.nameField.text.isEmpty ? "You can breathe easy, everything went OK." : "You can breathe easy, \(self.nameField.text)," + " everything went OK." let controller2 = UIAlertController(title:"Something Was Done", message: msg, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Phew!", style: .Cancel, handler: nil) controller2.addAction(cancelAction) self.presentViewController(controller2, animated: true, completion: nil) })
handler: is the code that is executed when this button is clicked.
Now create a new actionsheet with type alert
Alert Part IIIChange let yesAction = UIAlertAction(title: "Yes, I'm sure!", style: .Destructive, handler: nil) To let yesAction = UIAlertAction(title: "Yes, I'm sure!", style: .Destructive, handler: { action in let msg = self.nameField.text.isEmpty ? "You can breathe easy, everything went OK." : "You can breathe easy, \(self.nameField.text)," + " everything went OK." let controller2 = UIAlertController(title:"Something Was Done", message: msg, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Phew!", style: .Cancel, handler: nil) controller2.addAction(cancelAction) self.presentViewController(controller2, animated: true, completion: nil) })
handler: is the code that is executed when this button is clicked.
Create a cancel button for the alert.
Alert Part IVChange let yesAction = UIAlertAction(title: "Yes, I'm sure!", style: .Destructive, handler: nil) To let yesAction = UIAlertAction(title: "Yes, I'm sure!", style: .Destructive, handler: { action in let msg = self.nameField.text.isEmpty ? "You can breathe easy, everything went OK." : "You can breathe easy, \(self.nameField.text)," + " everything went OK." let controller2 = UIAlertController(title:"Something Was Done", message: msg, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Phew!", style: .Cancel, handler: nil) controller2.addAction(cancelAction) self.presentViewController(controller2, animated: true, completion: nil) })
handler: is the code that is executed when this button is clicked.
Present the alert