Tap gesture on custom Marker View using iOS-Charts - ios

I've created a custom marker view that loads from xib. I want to detect tap on the marker so that I can perform certain action on my VC. How can I do this?
PerformanceHomeViewController:
#IBOutlet weak var segmentBarChartView: SegmentBarChartView!
override func viewDidLoad() {
super.viewDidLoad()
self.segmentBarChartView.setupMarkerView(customText: "%# of 30 Agents")
}
SegmentBarChartView.swift
func setupMarkerView(customText: String) {
let customMarker: CustomMarker = (CustomMarker.viewFromXib() as? CustomMarker)!
customMarker.backgroundColor = .black
customMarker.setup(font: AIAMetrics.barChartTitleFont, textColor: .white, customString: customText)
customMarker.chartView = chartView
chartView.marker = customMarker
}
CustomMarkerView
#IBOutlet weak var textLabel: UILabel!
open var font: UIFont = .systemFont(ofSize: 12)
open var textColor: UIColor = .white
open var customString: String = ""
override open func awakeFromNib() {
self.offset.x = -self.frame.size.width / 2.0
self.offset.y = -self.frame.size.height - 7.0
}
public func setup(font: UIFont, textColor: UIColor, customString: String)
{
self.font = font
self.textColor = textColor
self.customString = customString
}
open override func refreshContent(entry: ChartDataEntry, highlight: Highlight) {
let labelString = String(format: customString, String(format: "%.0f", entry.y))
textLabel.text = labelString
layoutIfNeeded()
setLabel(labelString)
layoutIfNeeded()
}
open func setLabel(_ newLabel: String)
{
var size = CGSize()
size.width = textLabel.frame.size.width + 25 + 27
size.height = textLabel.frame.size.height + 20
size.height = max(size.height, 52)
self.frame.size = size
}
SegmentBarChartView is an xib that contains the Bar chart.
Can Anyone provide code example on what I should do so that I can detect tap on the marker view and perform some action on VC?

Related

How to Animate UIView on a line path without using UIBezierPath?

I have draw UIView say rectangle(player) and line, using context using draw(_ rect: CGRect) method.
I want to move the player on a line when clicking the play button.
I have searched lots of, but I found only for UIBezierpath but I want to use it with context
and I have tried some code name with playAnimation function.
class CanvasView : UIView{
// straight line
var lineStartPoint = CGPoint()
var lineEndpoint = CGPoint()
var lineStrokeList = [Lines]()
var lineDict : [String : Lines] = [:]
var lineActionDictionary : [String : [String : Lines]] = [:]
var linesPath : CGPath?
//player
var playerPoint : CGPoint?
var playerList = [Players]()
var playerDict : [Int : Players] = [:]
var selectedPlayerNumber : Int = 0
//action
var actionDict : [String : String] = ["1" : "1"]
var actionKeyIndex = String()
var actionList : [String] = [String]()
// common
var strokeWidth : CGFloat = 2.0
var currentColor = UIColor.black.cgColor
var imageSize : CGFloat = 30.0
private var selectedShape : ShapeType = .player
//MARK: Touches Began
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
switch selectedShape {
case .player:
playerPoint = touch.location(in: self)
playerDict.forEach { (key,value) in
if value.rect.contains(playerPoint ?? CGPoint()){
selectedPlayerNumber = Int(key)
self.playerDict.removeValue(forKey: selectedPlayerNumber)
return
}
}
setNeedsDisplay()
case .line:
let pos = touch.location(in: self)
lineStartPoint = pos
lineEndpoint = pos
setNeedsDisplay()
}
}
//MARK: Touches Moved
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let isfreeDrawSelected = isfreeDrawSelected
switch selectedShape {
case .player:
playerPoint = touch.location(in: self)
setNeedsDisplay()
case .line:
lineEndpoint = touch.location(in: self)
setNeedsDisplay()
}
}
//MARK: Touches Ended
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
switch selectedShape {
case .player:
if playerPoint != nil {
let point = CGPoint(x: playerPoint!.x, y: playerPoint!.y)
let x = playerPoint!.x - 15
let y = playerPoint!.y - 15
let playerRect = CGRect(x: x, y: y, width: imageSize, height: imageSize)
let playerstruct = Players(point: point,rect: playerRect)
playerList.append(playerstruct)
playerDict[selectedPlayerNumber] = playerstruct
playerPoint = nil
selectedPlayerNumber += 1
setNeedsDisplay()
}
case .line:
lineEndpoint = touch.location(in: self)
if !playerDict.isEmpty{
if lineActionDictionary[actionKeyIndex]?[String(selectedPlayerNumber)] != nil{
let alert = UIAlertController(title: "", message: "You can't add mutiple lines for action \(actionKeyIndex)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { alertAction in
debugPrint(self.lineActionDictionary)
}))
UIApplication.shared.windows
.last?.rootViewController?
.present(alert, animated: false, completion: nil)
}
else{
let line = Lines(startPoint: lineStartPoint, endPoint: lineEndpoint, color: currentColor, width: strokeWidth)
lineStrokeList.append(line)
lineDict[String(selectedPlayerNumber)] = line
if lineActionDictionary[actionKeyIndex] != nil {
lineActionDictionary[actionKeyIndex]!.updateValue(line, forKey: String(selectedPlayerNumber))
}else{
lineActionDictionary[actionKeyIndex] = lineDict
}
}
lineStartPoint = CGPoint()
lineEndpoint = CGPoint()
lineDict.removeAll()
setNeedsDisplay()
}
}
}
//MARK: Draw
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
if playerPoint != nil {
let x = (playerPoint?.x)! - 15
let y = (playerPoint?.y)! - 15
let player = CGRect(x: x, y: y, width: imageSize, height: imageSize)
context.addRect(player)
context.drawPath(using: .stroke)
linesPath = context.path
}
if !playerDict.isEmpty{
playerDict.forEach { (key,value) in
let x = value.point.x - 15
let y = value.point.y - 15
let player = CGRect(x: x, y: y, width: imageSize, height: imageSize)
let colorView = UIView(frame: player)
context.addRect(player)
context.drawPath(using: .stroke)
}
}
if lineStartPoint.x > 0 && lineEndpoint.y > 0{
context.setLineCap(.round)
context.setLineWidth(2.0)
context.move(to: lineStartPoint)
context.addLine(to: lineEndpoint)
context.setStrokeColor(UIColor.black.cgColor)
context.strokePath()
}
if !lineActionDictionary.isEmpty{
lineActionDictionary.forEach { (actionkey,actionvalue) in
actionvalue.forEach { (playerkey,playervalue) in
let startPoint = playervalue.startPoint
let endPoint = playervalue.endPoint
let color = playervalue.color
let width = playervalue.width
context.setLineCap(.round)
context.setLineWidth(width)
context.move(to: startPoint)
context.addLine(to: endPoint)
context.setStrokeColor(color)
context.strokePath()
}
}
}
}
func selectedShape(selctedShapes : ShapeTypes) {
selectedShape = selctedShapes
}
func playAnimation(){
switch selectedShape {
case .player:
break
case .line:
let player = playerList.first
let views = UIView(frame: player!.rect)
views.alpha = 1.0
UIView.animate(withDuration: 0.25, animations: {
views.frame = CGRect(x: 0, y: 10, width: 20, height: 20)
}, completion: {
(value: Bool) in
debugPrint(">>> Animation done.")
})
}
}
}
#ShapeTypes Enum
enum ShapeTypes : Int {
case player = 0
case line
}
#UIViewController
#available(iOS 14.0, *)
class TestVC : UIViewController{
#IBOutlet weak var colorPicker: UIImageView!
#IBOutlet weak var sliderMaxValueLbl: UILabel!
#IBOutlet weak var radiusSlider: UISlider!
#IBOutlet weak var tv: CanvasView!
#IBOutlet weak var shapeSegment : UISegmentedControl!
#IBOutlet weak var playerFormationPickerDoneBtn: UIButton!
#IBOutlet weak var playerFormationPicker: UIPickerView!
#IBOutlet weak var playerFormationTF: UITextField!
#IBOutlet weak var actionPickerDoneBtn: UIButton!
#IBOutlet weak var actionPicker: UIPickerView!
#IBOutlet weak var actionPickerTF: UITextField!
#IBOutlet weak var addActionBtn: UIBarButtonItem!
//playerformation pickerview
var playerFormationPickerData = String()
var playerFormationPickerSelectedIndex = Int()
var isPlayerFormationSelected : Bool = false
var playerViewArray: [PlayerView] = []
var pickerViewListData: [String] = [String]()
//action pickerview
var actionPickerData = String()
var actionPickerSelectedIndex = Int()
#IBAction func actionPickerDoneButtonAction(_ sender: UIButton) {
actionPickerDoneBtn.isHidden = true
actionPicker.isHidden = true
actionPickerTF.text = actionPickerData
tv.actionKeyIndex = actionPickerTF.text?.components(separatedBy: " ").last ?? ""
debugPrint(tv.actionKeyIndex)
}
func setSliderThumb(_ color: UIColor, _ width : CGFloat) {
let circleImage = makeCircleWith(size: CGSize(width: width, height: width),
backgroundColor: color)
radiusSlider.setThumbImage(circleImage, for: .normal)
radiusSlider.setThumbImage(circleImage, for: .highlighted)
}
fileprivate func makeCircleWith(size: CGSize, backgroundColor: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(backgroundColor.cgColor)
context?.setStrokeColor(UIColor.black.cgColor)
let bounds = CGRect(origin: .zero, size: size)
context?.addEllipse(in: bounds)
context?.drawPath(using: .fill)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
#IBAction func radiusSliderAction(_ sender: UISlider) {
let radius = Int(radiusSlider.value)
tv.radius = CGFloat(radius)
sliderMaxValueLbl.text = String(radius)
}
#IBAction func playAnimationAction(_ sender: UIBarButtonItem) {
tv.playAnimation()
}
override func viewDidLoad() {
super.viewDidLoad()
radiusSlider.minimumValue = 30
radiusSlider.maximumValue = 100
radiusSlider.value = 0
sliderMaxValueLbl.text = String(Int(radiusSlider.value))
setSliderThumb(UIColor.white, 20)
if let img = UIImage(named: "ground") { //background image
UIGraphicsBeginImageContext(tv.frame.size)
img.draw(in: tv.bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = image {
tv.backgroundColor = UIColor(patternImage: image)
tv.contentMode = .scaleAspectFill
}
}
actionPicker.delegate = self
actionPicker.dataSource = self
actionPicker.isHidden = true
actionPickerTF.delegate = self
actionPickerTF.textAlignment = .center
actionPickerTF.placeholder = "Select action"
actionPickerDoneBtn.isHidden = true
actionPickerDoneBtn.tintColor = .systemBlue
tv.actionKeyIndex = tv.actionDict["1"] ?? ""
tv.actionList = ["action \(tv.actionKeyIndex)"]
actionPickerData = tv.actionList[0]
actionPickerTF.text = actionPickerData
tv.currentColor = UIColor.black.cgColor
}
#IBAction func addActionButton(_ sender: UIBarButtonItem) {
let count = tv.actionList.count + 1
let element = tv.lineActionDictionary.keys.max()
// let element = tv.actionDict.values.max() // find max dict value
guard let maxValue = element?.first?.wholeNumberValue else { return }
debugPrint(maxValue)
tv.actionKeyIndex = String(maxValue + 1)
actionPickerTF.text = "action \(tv.actionKeyIndex)"
tv.actionList.append("action \(tv.actionKeyIndex)")
actionPicker.reloadAllComponents()
}
#IBAction func selectShapeSegmentAction(_ sender: UISegmentedControl) {
let selectShape : ShapeType = ShapeTypes(rawValue: shapeSegment.selectedSegmentIndex) ?? .player
tv.selectedShape(selctedShape: selectShape)
}
}
#available(iOS 14.0, *)
extension TestVC : UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == actionPicker{
actionPickerData = tv.actionList[row]
actionPickerTF.text = actionPickerData
actionPickerSelectedIndex = actionPicker.selectedRow(inComponent: 0)
}
}
}
#available(iOS 14.0, *)
extension TestVC : UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return tv.actionList.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return tv.actionList[row]
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
var title = UILabel()
if let view = view {
title = view as! UILabel
}
if pickerView == actionPicker {
title.text = tv.actionList[row]
}
title.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium)
title.textColor = UIColor.black
title.textAlignment = .center
return title
}
}
Lets say you have some customView and you want to simply temporary move it a little bit down. Here is lightweight solution.
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
func animateGoingDown() {
UIView.animate(withDuration: 0.5) {
self.customView.transform = CGAffineTransform(translationX: 0, y: 200)
}
}
func animateGoingToOriginalPosition() {
UIView.animate(withDuration: 0.5) {
self.customView.transform = .identity
}
}
Howefully this is what you are searching for. If you have some questions, do not hesitate to ask.

Autoresize infowindow from xib file depended from the content in swift

I try to resize my custom infowindow which is created in a xib file from a UIView.The width depends from content of the window, but i have not find any solution.I tried everything in the storyboard but nothing happens.I have upload a screenshot to see my problem:
Here is my code from the UIView of the xib
public protocol nonPaidDelegate: class {
func didTapMapsSelectButton()
}
class MapInfoWindow: UIView {
#IBOutlet weak var titleInfo: UILabel!
#IBOutlet weak var adressInfo: UILabel!
#IBOutlet weak var buttonAction: UIButton!
open var delegate:nonPaidDelegate?
#IBAction func didTapInButton(_ sender: Any) {
self.delegate?.didTapMapsSelectButton()
print("button tapped")
}
class func instanceFromNib() -> UIView {
return UINib(nibName: "MapInfoWindowView", bundle: nil).instantiate(withOwner: self, options: nil).first as! UIView
}
In my viewcontroller i call the MapInfoWindow
var infoWindow = MapInfoWindow()
infoWindow = loadNiB()
and i create the infoWindow UIView for the marker:
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
if let venueItem = marker.userData as? Venue {
infoWindow.titleInfo?.text = venueItem.name
infoWindow.adressInfo?.text = venueItem.locationName
NSLog(venueItem.name!)
} else {
NSLog("Did tap a normal marker")
}
return UIView()
}
}
You can achieve your goal programmatically like this,I have used two label(titleLabel & snippetLabel):
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
let infoWindowView = UIView()
let titleStringWidth = marker.title?.widthOfString(usingFont: UIFont.boldSystemFont(ofSize: 13.0))
var infoWidth = 0
if titleStringWidth!+10>self.view.frame.size.width - 50 {
infoWindowView.frame.size.width = self.view.frame.size.width - 50
infoWidth = Int(self.view.frame.size.width - 50.0)
}else {
infoWindowView.frame.size.width = titleStringWidth!+10
infoWidth = Int(titleStringWidth!)+10
}
infoWindowView.frame.size.width = self.view.frame.size.width - 50
infoWindowView.backgroundColor = UIColor.white
let titleLabel = UILabel()
titleLabel.frame.size.width = infoWindowView.frame.size.width-10
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.font = UIFont.boldSystemFont(ofSize: 13.0)
titleLabel.frame.origin.x = 3
titleLabel.frame.origin.y = 5
titleLabel.text = "your text"
titleLabel.textAlignment = .center
titleLabel.sizeToFit()
let actualNumberOfLinesForTiltle = titleLabel.numberOfVisibleLines
titleLabel.frame.size.height = CGFloat(actualNumberOfLinesForTiltle*20)
let snippetLabel = UILabel()
snippetLabel.frame.size.width = infoWindowView.frame.size.width-10
snippetLabel.numberOfLines = 0
snippetLabel.lineBreakMode = .byWordWrapping
snippetLabel.font = UIFont.boldSystemFont(ofSize: 13.0)
snippetLabel.text = "your text"
snippetLabel.textAlignment = .center
snippetLabel.sizeToFit()
let snippet_y = 20*actualNumberOfLinesForTiltle+10
let actualNumberOfLinesForSnippet = snippetLabel.numberOfVisibleLines
snippetLabel.frame.origin.x = 3
snippetLabel.frame.origin.y = CGFloat(snippet_y)
snippetLabel.frame.size.height = CGFloat(actualNumberOfLinesForSnippet*20)
let visibleHeightOfView = 15+actualNumberOfLinesForTiltle*20+actualNumberOfLinesForSnippet*20
infoWindowView.frame = CGRect(x: 0, y: 0, width: infoWidth, height: visibleHeightOfView)
infoWindowView.addSubview(titleLabel)
infoWindowView.addSubview(snippetLabel)
return infoWindowView
}
and add this extension
extension UILabel {
var numberOfVisibleLines: Int {
let textSize = CGSize(width: CGFloat(self.frame.size.width), height: CGFloat(MAXFLOAT))
let rHeight: Int = lroundf(Float(self.sizeThatFits(textSize).height))
let charSize: Int = lroundf(Float(self.font.pointSize))
return rHeight / charSize
}
}
extension String {
func widthOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSFontAttributeName: font]
let size = self.size(attributes: fontAttributes)
return size.width
}

how to define a label by a tag

i try a make a cloud of tag, and i have trouble with how to determine which label was pressed, for to the change color it. if i use like viewq.viewWithTag(1) it work but how i can understand what a label i press ? for change value. Maybe i need a make class ? because i want (if u press once, set color red and some action, if again it set blue color again and make some action)
//
// ViewController.swift
// weqddwqd
//
// Created by Jacket on 4/2/18.
// Copyright © 2018 TryFit. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var viewq: UIView!
var arrq: [String] = ["Hello", "World", "of", "Tags"]
var tags: [Int] = Array()
override func viewDidLoad() {
super.viewDidLoad()
createTagsLabel(arrq)
}
}
extension ViewController {
func createTagsLabel(_: [String]) {
var xPos:CGFloat = 15.0
var ypos: CGFloat = 130.0
var tag: Int = 0
for word in arrq {
let width = word.widthOfString(usingFont: UIFont(name:"verdana", size: 13.0)!)
let checkWholeWidth = CGFloat(xPos) + CGFloat(width) + CGFloat(13.0) + CGFloat(25.5)
if checkWholeWidth > UIScreen.main.bounds.size.width - 30.0 {
xPos = 15.0
ypos = ypos + 29.0 + 8.0
}
let textlable = UILabel(frame: CGRect(x: xPos, y: ypos, width: width + 18, height: 18))
textlable.layer.borderWidth = 1.8
textlable.layer.cornerRadius = 8
textlable.layer.borderColor = UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0).cgColor
textlable.textColor = UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0)
textlable.text = word
textlable.font = UIFont(name: "verdana", size: 13.0)
textlable.textAlignment = .center
textlable.isUserInteractionEnabled = true
ypos = ypos + 25
textlable.tag = tag
tags.append(tag)
tag = tag + 1
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapFunction(_:)))
//textlable.addTarget(self, action: #selector(tapFunction(_:)), for: .touchUpInside)
textlable.addGestureRecognizer(tap)
viewq.addSubview(textlable)
}
}
func tapFunction(_ recognizer: UITapGestureRecognizer) {
print(viewq.viewWithTag(1))
let tag = viewq.viewWithTag(1) as! UILabel
tag.layer.borderColor = UIColor .red.cgColor
tag.textColor = UIColor .red
print("Added")
}
}
extension String {
func widthOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSFontAttributeName: font]
let size = self.size(attributes: fontAttributes)
return size.width
}
func heightOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSFontAttributeName: font]
let size = self.size(attributes: fontAttributes)
return size.height
}
}
Your tapFunction can easily get the tapped view from the gesture. No tags required:
func tapFunction(_ recognizer: UITapGestureRecognizer) {
if let tappedLabel = recognizer.view as? UILabel {
tappedLabel.layer.borderColor = UIColor.red.cgColor
tappedLabel.textColor = .red
print("Added")
}
}

change inputAccessoryView's height issue in iOS 8.4

I made a MessageComposerView like this
import UIKit
protocol MessageComposerDelegate: NSObjectProtocol {
func messageDidChange(messageView: MessageComposerView, height: CGFloat)
func postMessage(message: String)
}
private let maxTextViewHeight: CGFloat = 100.0
class MessageComposerView: UIView, UITextViewDelegate {
#IBOutlet weak var textView: SAMTextView!
#IBOutlet weak var sendButton: UIButton!
weak var delegate:MessageComposerDelegate?
#IBAction func sendButtonAction(sender: UIButton) {
delegate?.postMessage(textView.text)
}
override func awakeFromNib() {
let borderColor = UIColor(white: 0.9, alpha: 1).CGColor
let layer = CALayer()
layer.backgroundColor = borderColor
layer.frame = CGRectMake(0, 0, CGRectGetWidth(UIScreen.mainScreen().bounds), 1.0)
self.layer.addSublayer(layer)
textView.backgroundColor = UIColor.whiteColor()
textView.layer.borderColor = borderColor
textView.layer.borderWidth = 1.0
textView.layer.cornerRadius = 5.0
textView.delegate = self
textView.layoutManager.allowsNonContiguousLayout = false
sendButton.backgroundColor = Color.Red.colorValue
sendButton.tintColor = UIColor.whiteColor()
sendButton.layer.cornerRadius = 5.0
}
//MARK: TextViewDelegate
func textViewDidChange(textView: UITextView) {
self.sendButton.enabled = !self.textView.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).isEmpty
textView.scrollEnabled = textView.contentSize.height >= maxTextViewHeight
let height = textView.scrollEnabled ? textView.contentSize.height : textView.intrinsicContentSize().height
delegate?.messageDidChange(self, height: min(height, maxTextViewHeight) + 16.0)
if let selectedTextRange = self.textView.selectedTextRange {
let caretRect = self.textView.caretRectForPosition(selectedTextRange.end);
let height = self.textView.textContainerInset.bottom + caretRect.size.height
self.textView.scrollRectToVisible(CGRectMake(caretRect.origin.x, caretRect.origin.y, caretRect.size.width, height), animated: true)
}
}
}
and in the ViewController when I increase the height of MessageComposerView:
func messageDidChange(messageView: MessageComposerView, height: CGFloat) {
messageView.bounds.size.height = height
self.reloadInputViews()
messageView.textView.reloadInputViews()
}
In iOS 9,It works well.
but in iOS 8.4,The textView and Button not change their frame rightly
So What should I do to fix it in iOS 8.4,Thank you!

IOS 6 to Swift2 update Slider

any chance someone to help me in this code? it is a Slider that changes the size of the Fonts in a Label. this worked in IOS6 but I am trying to run on Swift 2.Thanks in advance.
import UIKit
class ViewController: UIViewController {
#IBAction func defaultSlider1(sender: UISlider) {
UISlider *slide = (UISlider *)sender;
int fonts = (int)(slide.value);
NSString *newtext = NSlog("%d", fonts);
label.font = [UIFont systemFontOfSize:fonts];
label.text = newtext;
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
Please try following example (Demo):
import UIKit
class ViewController: UIViewController {
private var slider: UISlider!
private var label: UILabel!
private let minimumFontSize: Float = 16
private let maximumFontSize: Float = 48
override func viewDidLoad() {
super.viewDidLoad()
let width: CGFloat = view.bounds.width / 2
let height: CGFloat = 44.0
let size = CGSize(width: width, height: height)
let origin = CGPoint(x: self.view.center.x - (width / 2), y: self.view.center.y)
createSlider(origin, size: size)
createLabel(origin, size: size)
sliderAction()
}
func createSlider(origin: CGPoint, size: CGSize) {
let frame = CGRect(origin: origin, size: size)
self.slider = UISlider(frame: frame)
self.slider.addTarget(self,
action: Selector("sliderAction"),
forControlEvents: UIControlEvents.ValueChanged)
self.slider.minimumValue = minimumFontSize
self.slider.maximumValue = maximumFontSize
view.addSubview(self.slider)
}
func createLabel(origin: CGPoint, size: CGSize) {
let labelOrigin = CGPoint(x: origin.x, y: origin.y + size.height)
let frame = CGRect(origin: labelOrigin, size: size)
self.label = UILabel(frame: frame)
self.label.textAlignment = NSTextAlignment.Center
view.addSubview(self.label)
}
func sliderAction() {
let fontSize = CGFloat(self.slider.value)
self.label.font = UIFont.systemFontOfSize(fontSize)
self.label.text = "\(Int(fontSize))"
}
}
In case you're using Storyboards:
Add UISlider and UILabel to your View Controller Scene on the Storyboard
Insert #IBOutlets for each control (Ctrl+Drag from the control on the Storyboard to code, choose Outlet from Connection list)
Insert #IBAction for slider's Value Changed event (Ctrl+Drag from the slider control on the Storyboard to code, choose Action from Connection list)
You may end up with something like:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var slider: UISlider!
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.slider.minimumValue = 16
self.slider.maximumValue = 48
self.sliderAction()
}
#IBAction func sliderValueChangedAction(sender: UISlider) {
self.sliderAction()
}
private func sliderAction() {
let fontSize = CGFloat(self.slider.value)
self.label.font = UIFont.systemFontOfSize(fontSize)
self.label.text = "\(Int(fontSize))"
}
}

Resources