Get text characters frame on UILabel - ios

I've a ULabel on my view controller. So, If user draws line over the UILabel then I've to print text from the UILabel by user drawn range. This is the purpose.
My question is,
How to get character frames from the CGPoint ranges (start & end) on UILabel? I simply want to print the string as I coded.
Diagram:
Drawing:
String Range:
I don't have any clue to solve this problem. So, Please help to find the solution. Thanks in advance...
Code:
import UIKit
class ViewController: UIViewController {
let font: UIFont = UIFont.systemFont(ofSize: 16, weight: .medium)
lazy var label: UILabel = {
let label = UILabel()
label.text = "The orange is the fruit of various citrus"
label.font = font
label.textAlignment = .left
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.leftAnchor.constraint(equalTo: view.leftAnchor),
label.rightAnchor.constraint(equalTo: view.rightAnchor),
label.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
label.textColor = .white
label.backgroundColor = .black
let button = UIButton(frame: .init(x: (view.frame.width/2)-30, y: 80, width: 60, height: 40))
button.backgroundColor = .gray
button.setTitle("Print", for: .normal)
button.addTarget(self, action: #selector(actionButton), for: .touchUpInside)
view.addSubview(button)
}
#objc func actionButton(){
//Any demo points.
let p1 = CGPoint.zero
let p2 = CGPoint(x: 70, y: 0)
print("String: ")
}
}

Try this in Swift Playground
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let label = UILabelExtended()
label.frame = view.bounds
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.numberOfLines = 0
label.text = "Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book."
label.textColor = .black
view.addSubview(label)
self.view = view
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
class UILabelExtended: UILabel {
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: .zero)
var textStorage = NSTextStorage()
lazy var gesture = TouchGestureRecognizer(target: self, action: #selector(onSwipe(gesture:)))
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
isUserInteractionEnabled = true
addGestureRecognizer(gesture)
}
override var text: String? {
get {
return super.attributedText?.string
}
set {
let attrs: [NSAttributedString.Key : Any] = [.font: font!]
attributedText = NSAttributedString(string: newValue ?? "", attributes: attrs)
updateTextContainer()
}
}
var startIndex = -1
var endIndex = -1
var startPoint = CGPoint.zero
var endPoint = CGPoint.zero
#objc func onSwipe(gesture: UIGestureRecognizer) {
switch gesture.state {
case .began:
updateBoundingBox()
let start = getTextIndexFrom(point: gesture.location(in: self))
startIndex = start.0
startPoint = start.1
case .changed:
let end = getTextIndexFrom(point: gesture.location(in: self))
endIndex = end.0
endPoint = end.1
if let text = attributedText?.string, startIndex > -1 {
if startIndex > endIndex { swap(&startIndex, &endIndex) }
let s = text.index(text.startIndex, offsetBy: startIndex)
let e = text.index(text.startIndex, offsetBy: endIndex)
print(startPoint, endPoint, text[s...e])
}
default:
break
}
setNeedsDisplay()
}
var textBoundingBox: CGRect = .zero
private func updateBoundingBox() {
textBoundingBox = layoutManager.usedRect(for: textContainer)
textBoundingBox.origin = CGPoint(x: bounds.midX - textBoundingBox.size.width / 2, y: bounds.midY - textBoundingBox.size.height / 2)
}
private func getTextIndexFrom(point: CGPoint) -> (Int, CGPoint) {
let touchPoint = CGPoint(x: point.x - textBoundingBox.origin.x, y: point.y - textBoundingBox.origin.y)
let index = layoutManager.characterIndex(for: touchPoint, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
return (index, touchPoint)
}
private func updateTextContainer() {
textStorage = .init(attributedString: attributedText!)
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)
textContainer.lineFragmentPadding = 0.0
textContainer.lineBreakMode = lineBreakMode
textContainer.maximumNumberOfLines = numberOfLines
}
override func layoutSubviews() {
super.layoutSubviews()
textContainer.size = bounds.size
}
override func draw(_ rect: CGRect) {
super.draw(rect)
if let context = UIGraphicsGetCurrentContext() {
context.setStrokeColor(UIColor.red.cgColor)
context.setLineWidth(2)
context.move(to: startPoint)
context.addLine(to: endPoint)
context.addRect(textBoundingBox)
context.strokePath()
}
}
}
class TouchGestureRecognizer: UIGestureRecognizer, UIGestureRecognizerDelegate {
override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
delegate = self
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
state = .began
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
state = .changed
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
state = .ended
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
state = .cancelled
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return !(otherGestureRecognizer is TouchGestureRecognizer)
}
}

Related

Is there any way to implement before and after view functionality in swift ios for side by side image comparison as we move the slider left or right?

Attached video here
I want create this before and after view for side by side image comparison image here
You can do this with a layer mask.
Essentially:
private let maskLayer = CALayer()
maskLayer.backgroundColor = UIColor.black.cgColor
leftImage.layer.mask = maskLayer
var r = bounds
r.size.width = bounds.width * pct
maskLayer.frame = r
That will "clip" the image view and show only the portion covered by the mask layer.
Here's a complete example...
Using these "before" (left-side) and "after" (right-side) images:
With this sample custom view:
class RevealImageView: UIImageView {
public var leftImage: UIImage? {
didSet {
if let img = leftImage {
leftImageLayer.contents = img.cgImage
}
}
}
public var rightImage: UIImage? {
didSet {
if let img = rightImage {
self.image = img
}
}
}
// private properties
private let leftImageLayer = CALayer()
private let maskLayer = CALayer()
private let lineView = UIView()
private var pct: CGFloat = 0.5 {
didSet {
updateView()
}
}
convenience init() {
self.init(frame: .zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
// any opaque color
maskLayer.backgroundColor = UIColor.black.cgColor
leftImageLayer.mask = maskLayer
// the "reveal" image layer
layer.addSublayer(leftImageLayer)
// the vertical line
lineView.backgroundColor = .lightGray
addSubview(lineView)
isUserInteractionEnabled = true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let t = touches.first
else { return }
let loc = t.location(in: self)
pct = loc.x / bounds.width
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let t = touches.first
else { return }
let loc = t.location(in: self)
pct = loc.x / bounds.width
}
private func updateView() {
// move the vertical line to the touch point
lineView.frame = CGRect(x: bounds.width * pct, y: bounds.minY, width: 1, height: bounds.height)
// update the "left image" mask to the touch point
var r = bounds
r.size.width = bounds.width * pct
// disable layer animation
CATransaction.begin()
CATransaction.setDisableActions(true)
maskLayer.frame = r
CATransaction.commit()
}
override func layoutSubviews() {
super.layoutSubviews()
leftImageLayer.frame = bounds
updateView()
}
}
and this simple example controller:
class RevealImageTestVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
guard let leftIMG = UIImage(named: "before"),
let rightIMG = UIImage(named: "after")
else {
return
}
let revealView = RevealImageView()
revealView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(revealView)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
revealView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
revealView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
revealView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
// give reveal view the same aspect ratio as the image
revealView.heightAnchor.constraint(equalTo: revealView.widthAnchor, multiplier: leftIMG.size.height / leftIMG.size.width),
])
revealView.leftImage = leftIMG
revealView.rightImage = rightIMG
}
}
We get this - the vertical line and the "viewable" portion of the images will move as you touch-and-drag:

How to edit and update number on same player?

my app part is based on canvas.
#What I want to do?
I need dictionary to track and save particular player's key and value.because, I want to store player1 on key "1" and player2 on key "2", suppose user change player 2's number, then player 2's number change not key "2".
I can place multiple players (cashapelayers - with text),
on imageview. and can edit text label on double click for same player.
my issue is, whenever i click second time on same player, it shows wrong number, as well when click okay it creates new player.
what i want is to edit a player's label(number) with different number,
and don't create a new one till I click on imageview.
I have try to create playerview in touchedEnded but I'm fail, also try to search for the same issue on other resources.
I have added some images for reference.
class AddPlayerStruct {
var addPlayerViewStruct : AddPlayerView?
var addPlayerViewsArrStruct : [AddPlayerView] = []
var Label = UILabel()
}
import UIKit
class ViewController: UIViewController {
//MARK: AddPlayerView Variables
var addPlayerView : AddPlayerView?
var addPlayerViews: [AddPlayerView] = []
var draggedAddPlayer: AddPlayerView?
let addPlayerWidth : CGFloat = 40
var addPlayerDict : [String : AddPlayerStruct] = [:]
var playerCount : Int = 1
var label = UILabel()
var isDobuleClick : Bool = false
#IBOutlet weak var images: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let draggedAddPlayer = draggedAddPlayer, let point = touches.first?.location(in: images) else {
return
}
draggedAddPlayer.center = point
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Do nothing if a circle is being dragged
// or if we do not have a coordinate
guard draggedAddPlayer == nil, let point = touches.first?.location(in: images) else {
return
}
// Do not create new circle if touch is in an existing circle
// Keep the reference of the (potentially) dragged circle
if let draggedAddPlayer = addPlayerViews.filter({ UIBezierPath(ovalIn: $0.frame).contains(point) }).first {
self.draggedAddPlayer = draggedAddPlayer
return
}
// Create new circle and store in dict
let rect = CGRect(x: point.x - 20, y: point.y - 20, width: addPlayerWidth, height: addPlayerWidth)
addPlayerView = AddPlayerView(frame: rect)
addPlayerView?.backgroundColor = .white
addPlayerView?.isUserInteractionEnabled = true
addPlayerView?.image = UIImage(named: "player")
addPlayerView?.tintColor = .systemBlue
addPlayerViews.append(addPlayerView!)
images.addSubview(addPlayerView!)
// The newly created view can be immediately dragged
draggedAddPlayer = addPlayerView
//Add Player label as Number
// playerCount = addPlayerDict.count + 1
var addPlayerStruct = AddPlayerStruct()
label = UILabel(frame: CGRect(x: rect.width / 2 - 8, y: rect.height / 2 + 5, width: 16, height: 10))
if addPlayerStruct.Label.text == nil{
label.text = String(addPlayerDict.count + 1)
}
label.font = UIFont(name: "Helvetica" , size: 10)
label.textColor = UIColor.white
label.textAlignment = NSTextAlignment.center
label.isUserInteractionEnabled = true
addPlayerView!.addSubview(label)
debugPrint(addPlayerDict)
addPlayerStruct.addPlayerViewStruct = addPlayerView
addPlayerStruct.addPlayerViewsArrStruct.append(contentsOf: addPlayerViews)
addPlayerDict.updateValue(addPlayerStruct, forKey: String(addPlayerDict.count + 1))
debugPrint(addPlayerDict)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
draggedAddPlayer = nil
var selectedPlayerKey = String()
var addPlayerStruct = AddPlayerStruct()
var selectedPoint = CGPoint()
if isDobuleClick == true {
guard let point = touches.first?.location(in: images) else {
return
}
//TODO: check which dict key's playerview has same point
addPlayerDict.forEach { (key,value) in
debugPrint(key)
debugPrint(value)
// debugPrint("before \(addPlayerDict.count)")
//TODO: get selected dict key and get all data of it
guard let points = value.addPlayerViewStruct?.frame.contains(point) else { return }
if points{
selectedPlayerKey = key
selectedPoint = point
addPlayerViews.append(contentsOf: value.addPlayerViewsArrStruct)
debugPrint(addPlayerViews.last)
addPlayerView = value.addPlayerViewStruct //selected playerview
debugPrint(selectedPlayerKey)
// show data on alertview textfield
let alert = UIAlertController(title: "Player Number", message: "Enter new player Number", preferredStyle: .alert)
alert.addTextField { textData in
if addPlayerStruct.Label.text == nil{
textData.text = selectedPlayerKey
}else{
textData.text = addPlayerStruct.Label.text
}
}
// get changed data from textfield and save back to same dict key's playerview - Don't change key.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
let textfield = alert.textFields?[0]
addPlayerStruct.Label.text = textfield?.text!
// let index = self.addPlayerDict.index(forKey: selectedPlayerKey)
addPlayerStruct.addPlayerViewStruct = self.addPlayerView
self.draggedAddPlayer = self.addPlayerView
self.addPlayerViews.removeLast()
self.addPlayerView?.removeFromSuperview() //selected playerview removed from iamgeview
//
// // Show on playerview
//
let rect = CGRect(x: selectedPoint.x - 20, y: selectedPoint.y - 20, width: self.addPlayerWidth, height: self.addPlayerWidth)
self.addPlayerView = AddPlayerView(frame: rect)
self.addPlayerView?.backgroundColor = .white
self.addPlayerView?.isUserInteractionEnabled = true
self.addPlayerView?.image = UIImage(named: "player")
self.addPlayerView?.tintColor = .systemBlue
self.addPlayerViews.append(self.addPlayerView!)
self.images.addSubview(self.addPlayerView!)
self.label = UILabel(frame: CGRect(x: rect.width / 2 - 8, y: rect.height / 2 + 5, width: 16, height: 10))
self.label.text = textfield?.text!
self.label.font = UIFont(name: "Helvetica" , size: 10)
self.label.textColor = UIColor.white
self.label.textAlignment = NSTextAlignment.center
self.label.isUserInteractionEnabled = true
self.addPlayerView!.addSubview(self.label)
debugPrint(self.addPlayerDict.count)
self.addPlayerDict.updateValue(addPlayerStruct, forKey: selectedPlayerKey)
debugPrint(addPlayerStruct.addPlayerViewStruct?.frame)
debugPrint(self.addPlayerDict.count)
}))
self.present(alert, animated: false)
}
}
}
isDobuleClick = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.isDobuleClick = false
}
}
}
#AddPlayerView
class AddPlayerView : UIImageView{
var shapeLayer = CAShapeLayer()
var addPlayerPath = UIBezierPath()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup(){
self.backgroundColor = .clear
// let shapeLayer = CAShapeLayer()
addPlayerPath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2, y: frame.size.height / 2), radius: 20, startAngle: 0, endAngle: 360, clockwise: true)
shapeLayer.path = addPlayerPath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
self.layer.addSublayer(shapeLayer)
}
}
You have a decent approach, but a couple tips...
Your class and var naming is rather confusing. For example, instead of naming your image view images it makes much more sense to name it something like playingFieldImageView. And, instead of AddPlayerView (which sounds like an action), just name it PlayerView.
You don't need to keep a separate array of player views or a dictionary of player structs... When you add a PlayerView as a subview of playingFieldImageView, you can track it with the .subviews property of playingFieldImageView.
You can move a lot of the logic you're using to manage the player view into the player view class... along these lines:
class PlayerView : UIImageView {
public var playerNumber: Int = 0 {
didSet {
playerLabel.text = "\(playerNumber)"
}
}
private let shapeLayer = CAShapeLayer()
private let playerLabel: UILabel = {
let v = UILabel()
v.font = UIFont(name: "Helvetica" , size: 10)
v.textColor = .white
v.textAlignment = NSTextAlignment.center
v.text = "0"
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
self.isUserInteractionEnabled = true
self.backgroundColor = .white
self.tintColor = .systemBlue
if let img = UIImage(named: "player") {
self.image = img
} else {
if let img = UIImage(systemName: "person.fill") {
self.image = img
} else {
self.backgroundColor = .green
}
}
// if using as a mask, can be any opaque color
shapeLayer.fillColor = UIColor.black.cgColor
// assuming you want a "round" view
//self.layer.addSublayer(shapeLayer)
self.layer.mask = shapeLayer
// add and constrain the label as a subview
addSubview(playerLabel)
NSLayoutConstraint.activate([
playerLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
playerLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
playerLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5.0),
])
}
override func layoutSubviews() {
// update the mask path here (we have accurate bounds)
shapeLayer.path = UIBezierPath(ovalIn: bounds).cgPath
}
}
Now you can add a new PlayerView and assign its .playerNumber ... instead of all of the set image, add label, etc. And, when the user wants to change the "player number" you can update the .playerNumber property instead of removing / re-creating views.
When trying to track touches and taps (particularly double-taps), it is much easier to add a double-tap gesture recognizer to the subview itself.
Here's that same PlayerView class, but with a gesture recognizer -- and a closure to tell the controller that it was double-tapped:
class PlayerView : UIImageView {
// closure to tell the controller this view was double-tapped
public var gotDoubleTap: ((PlayerView) -> ())?
public var playerNumber: Int = 0 {
didSet {
playerLabel.text = "\(playerNumber)"
}
}
private let shapeLayer = CAShapeLayer()
private let playerLabel: UILabel = {
let v = UILabel()
v.font = UIFont(name: "Helvetica" , size: 10)
v.textColor = .white
v.textAlignment = NSTextAlignment.center
v.text = "0"
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
self.isUserInteractionEnabled = true
self.backgroundColor = .white
self.tintColor = .systemBlue
if let img = UIImage(named: "player") {
self.image = img
} else {
if let img = UIImage(systemName: "person.fill") {
self.image = img
} else {
self.backgroundColor = .green
}
}
// if using as a mask, can be any opaque color
shapeLayer.fillColor = UIColor.black.cgColor
// assuming you want a "round" view
//self.layer.addSublayer(shapeLayer)
self.layer.mask = shapeLayer
// add and constrain the label as a subview
addSubview(playerLabel)
NSLayoutConstraint.activate([
playerLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
playerLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
playerLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5.0),
])
// add a double-tap gesture recognizer
let g = UITapGestureRecognizer(target: self, action: #selector(doubleTapHandler(_:)))
g.numberOfTapsRequired = 2
addGestureRecognizer(g)
}
override func layoutSubviews() {
// update the mask path here (we have accurate bounds)
shapeLayer.path = UIBezierPath(ovalIn: bounds).cgPath
}
#objc func doubleTapHandler(_ g: UITapGestureRecognizer) {
// tell the controller we were double-tapped
gotDoubleTap?(self)
}
}
You can now simplify all of your touch code to handle only adding new or moving the player views.
Here's an example controller class, using the above PlayerView class:
class AddPlayerViewController: UIViewController {
//MARK: AddPlayerView Variables
// we can declare this as a standard UIView
var draggedPlayerView: UIView?
let playerViewWidth : CGFloat = 40
#IBOutlet var playingFieldImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
playingFieldImageView.isUserInteractionEnabled = true
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let draggedAddPlayer = draggedPlayerView, let point = touches.first?.location(in: playingFieldImageView) else {
return
}
draggedAddPlayer.center = point
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Do nothing if a PlayerView is being dragged
// or if we do not have a coordinate
guard draggedPlayerView == nil, let point = touches.first?.location(in: playingFieldImageView) else {
return
}
// Do not create new PlayerView if touch is in an existing circle
// Keep the reference of the (potentially) dragged circle
// filter only subviews which are PlayerView class (in case we've added another subview type)
if let draggedAddPlayer = playingFieldImageView.subviews.filter({ $0 is PlayerView }).filter({ UIBezierPath(ovalIn: $0.frame).contains(point) }).first {
self.draggedPlayerView = draggedAddPlayer
return
}
// Create new PlayerView
let rect = CGRect(x: point.x - 20, y: point.y - 20, width: playerViewWidth, height: playerViewWidth)
let newPlayerView = PlayerView(frame: rect)
// give the new player the lowest available number
// for example, if we've created numbers:
// "1" "2" "3" "4" "5"
// we want to assign "6" to the new guy
// but... if the user has changed the 3rd player to "12"
// we'll have players:
// "1" "2" "12" "4" "5"
// so we want to assign "3" to the new guy
let nums = playingFieldImageView.subviews.compactMap{$0 as? PlayerView}.compactMap { $0.playerNumber }
var newNum: Int = 1
for i in 1..<nums.count + 2 {
if !nums.contains(i) {
newNum = i
break
}
}
newPlayerView.playerNumber = newNum
// set the double-tap closure
newPlayerView.gotDoubleTap = { [weak self] pv in
guard let self = self else { return }
self.changePlayerNumber(pv)
}
playingFieldImageView.addSubview(newPlayerView)
// The newly created view can be immediately dragged
draggedPlayerView = newPlayerView
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
draggedPlayerView = nil
}
// called when a PlayerView is double-tapped
func changePlayerNumber(_ playerView: PlayerView) {
// show data on alertview textfield
let alert = UIAlertController(title: "Player Number", message: "Enter new player Number", preferredStyle: .alert)
alert.addTextField { textData in
textData.text = "\(playerView.playerNumber)"
}
// get changed data from textfield and update the playerNumber for the PlayerView
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
guard let tf = alert.textFields?.first,
let newNumString = tf.text,
let newNumInt = Int(newNumString),
newNumInt != playerView.playerNumber
else {
// user entered something that was not a number, or
// tapped OK without changing the number
return
}
// don't allow a duplicate player number
let nums = self.playingFieldImageView.subviews.compactMap{$0 as? PlayerView}.compactMap { $0.playerNumber }
if nums.contains(newNumInt) {
let dupAlert = UIAlertController(title: "Duplicate PLayer Number", message: "Somebody else already has number: \(newNumInt)", preferredStyle: .alert)
dupAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
self.changePlayerNumber(playerView)
}))
self.present(dupAlert, animated: true)
} else {
playerView.playerNumber = newNumInt
}
}))
self.present(alert, animated: false)
}
}

Can a UIView assign a UITapGestureRecognizer to itself?

I'm trying to make a UIView that recognizes tap gestures, however taps are not ever correctly registered by the UIView. Here's the code for the UIView subclass itself:
import UIKit
class ActionCell: SignalTableCell, UIGestureRecognizerDelegate {
var icon: UIImageView!
var actionType: UILabel!
var actionTitle: UILabel!
var a:Action?
var tap:UITapGestureRecognizer?
required init(frame: CGRect) {
//
super.init(frame:frame)
tap = UITapGestureRecognizer(target: self, action: #selector(self.touchTapped(_:)))
tap?.delegate = self
addGestureRecognizer(tap!)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
tap = UITapGestureRecognizer(target: self, action: #selector(self.touchTapped(_:)))
tap?.delegate = self
addGestureRecognizer(tap!)
}
#objc func touchTapped(_ sender: UITapGestureRecognizer) {
print("OK")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.isUserInteractionEnabled = true
}
override func layoutSubviews() {
if(icon == nil) {
let rect = CGRect(origin: CGPoint(x: 10,y :20), size: CGSize(width: 64, height: 64))
icon = UIImageView(frame: rect)
addSubview(icon)
}
icon.image = UIImage(named:(a?.icon)!)
if(actionType == nil) {
let rect = CGRect(origin: CGPoint(x: 100,y :20), size: CGSize(width: 200, height: 16))
actionType = UILabel(frame: rect)
addSubview(actionType)
}
actionType.text = a.type
if(actionTitle == nil) {
let rect = CGRect(origin: CGPoint(x: 100,y :80), size: CGSize(width: 200, height: 16))
actionTitle = UILabel(frame: rect)
addSubview(actionTitle)
}
actionTitle.text = a?.title
}
func configure( a:Action ) {
self.a = a
}
override func setData( type:SignalData ) {
a = (type as! Action)
}
}
I'm simply trying to make it so that this UIView can, you know, know when it's tapped. Is this possible without adding a separate UIViewController? This seems as though it should be fairly simple but it doesn't appear to be, confusingly.
I've stepped through the code and the init method is called and the Gesture Recognizer is added but it doesn't trigger.
If its a table view cell, I'd recommend not using a tap gesture, since it might interfere with the didSelectRowAtIndexPath: and other delegate methods. But if you still wanna keep the tap gesture, try adding tap?.cancelsTouchesInView = false before addGestureRecognizer(tap!) and see if that works.
If you just want to know when its tapped, you could also override the following UIResponder method:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
// do your stuff
}
I think, it is easier to override touchesBegan method. Something like this:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touched")
super.touchesBegan(touches, with: event)
}
Most likely the actionType, ActionTitle, and icon are being tapped and the tap is not falling through because user interaction is disabled by default for labels and images. Set isUserInteractionEnabled = true for each of those fields that are subviews of the main view.
override func layoutSubviews() {
if(icon == nil) {
let rect = CGRect(origin: CGPoint(x: 10,y :20), size: CGSize(width: 64, height: 64))
icon = UIImageView(frame: rect)
icon.isUserInteractionEnabled = true
addSubview(icon)
}
icon.image = UIImage(named:(a?.icon)!)
if(actionType == nil) {
let rect = CGRect(origin: CGPoint(x: 100,y :20), size: CGSize(width: 200, height: 16))
actionType = UILabel(frame: rect)
actionType.isUserInteractionEnabled = true
addSubview(actionType)
}
actionType.text = a.type
if(actionTitle == nil) {
let rect = CGRect(origin: CGPoint(x: 100,y :80), size: CGSize(width: 200, height: 16))
actionTitle = UILabel(frame: rect)
actionTitle.isUserInteractionEnabled = true
addSubview(actionTitle)
}
actionTitle.text = a?.title
}

Zoom on UIView contained in UIScrollView

I have some trouble handling zoom on UIScrollView that contains many subviews. I already saw many answers on SO, but none of them helped me.
So, basically what I'm doing is simple : I have a class called UIFreeView :
import UIKit
class UIFreeView: UIView, UIScrollViewDelegate {
var mainUIView: UIView!
var scrollView: UIScrollView!
var arrayOfView: [UIView]?
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupView() {
// MainUiView
self.mainUIView = UIView(frame: self.frame)
self.addSubview(mainUIView)
// ScrollView
self.scrollView = UIScrollView(frame: self.frame)
self.scrollView.delegate = self
self.addSubview(self.scrollView)
}
func reloadViews(postArray:[Post]?) {
if let postArray = postArray {
print("UIFreeView::reloadVIew.postArraySize = \(postArray.count)")
let size: CGFloat = 80.0
let margin: CGFloat = 20.0
scrollView.contentSize.width = (size * CGFloat(postArray.count))+(margin*CGFloat(postArray.count))
scrollView.contentSize.height = (size * CGFloat(postArray.count))+(margin*CGFloat(postArray.count))
for item in postArray {
let view = buildPostView(item)
self.scrollView.addSubview(view)
}
}
}
fileprivate func buildPostView(_ item:Post) -> UIView {
// Const
let size: CGFloat = 80.0
let margin: CGFloat = 5.0
// Var
let view = UIView()
let textView = UITextView()
let backgroundImageView = UIImageView()
// Setup view
let x = CGFloat(UInt64.random(lower: UInt64(0), upper: UInt64(self.scrollView.contentSize.width)))
let y = CGFloat(UInt64.random(lower: UInt64(0), upper: UInt64(self.scrollView.contentSize.height)))
view.frame = CGRect(x: x,
y: y,
width: size,
height: size)
// Setup background view
backgroundImageView.frame = CGRect(x: 0,
y: 0,
width: view.frame.size.width,
height: view.frame.size.height)
var bgName = ""
if (item.isFromCurrentUser) {
bgName = "post-it-orange"
} else {
bgName = "post-it-white"
}
backgroundImageView.contentMode = .scaleAspectFit
backgroundImageView.image = UIImage(named: bgName)
view.addSubview(backgroundImageView)
// Setup text view
textView.frame = CGRect(x: margin,
y: margin,
width: view.frame.size.width - margin*2,
height: view.frame.size.height - margin*2)
textView.backgroundColor = UIColor.clear
textView.text = item.content
textView.isEditable = false
textView.isSelectable = false
textView.isUserInteractionEnabled = false
view.addSubview(textView)
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
view.addGestureRecognizer(gestureRecognizer)
return view
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.scrollView
}
func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
let translation = gestureRecognizer.translation(in: self.scrollView)
// note: 'view' is optional and need to be unwrapped
gestureRecognizer.view!.center = CGPoint(x: gestureRecognizer.view!.center.x + translation.x, y: gestureRecognizer.view!.center.y + translation.y)
gestureRecognizer.setTranslation(CGPoint.zero, in: self.scrollView)
}
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
This class is working perfectly, I can scroll through all my views, but I can't zoom-in and zoom-out in order to see less/more views on my screen.
I think the solution is simple, but I can't seem to find a real solution for my problem ..
Thanks !

Can anybody help me understand this code - iOS swift

This is the code of creating a custom segmented control i found over the Internet. I have a problem in understanding the last two functions, beginTrackingWithTouch and layoutSubviews. What are the purpose of these functions and what does their code do exactly
and finally, excuse this question. I'm still a beginner in iOS development and I'm just seeking help.
#IBDesignable class CustomSegmentedControl : UIControl {
private var labels = [UILabel]()
var items = ["Item 1","Item 2"] {
didSet {
setUpLabels()
}
}
var thumbView = UIView()
var selectedIndex : Int = 0 {
didSet {
displayNewSelectedIndex()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
func setupView() {
//layer.cornerRadius = frame.height / 2
layer.borderColor = UIColor.blackColor().CGColor
layer.borderWidth = 2
backgroundColor = UIColor.clearColor()
setUpLabels()
insertSubview(thumbView, atIndex: 0)
}
func setUpLabels() {
for label in labels {
label.removeFromSuperview()
}
labels.removeAll(keepCapacity: true)
for index in 1...items.count {
let label = UILabel(frame: CGRectZero)
label.text = items[index-1]
label.textAlignment = .Center
label.textColor = UIColor.blackColor()
self.addSubview(label)
labels.append(label)
}
}
func displayNewSelectedIndex() {
let label = labels[selectedIndex]
self.thumbView.frame = label.frame
}
override func layoutSubviews() {
super.layoutSubviews()
var selectFrame = self.bounds
let newWidth = CGRectGetWidth(selectFrame) / CGFloat(items.count)
selectFrame.size.width = newWidth
thumbView.frame = selectFrame
thumbView.backgroundColor = UIColor.grayColor()
//thumbView.layer.cornerRadius = thumbView.frame.height / 2
let labelHeight = self.bounds.height
let labelWidth = self.bounds.width / CGFloat(labels.count)
for index in 0..<labels.count {
let label = labels[index]
let xPosition = CGFloat(index) * labelWidth
label.frame = CGRectMake(xPosition, 0, labelWidth, labelHeight)
}
}
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
let location = touch.locationInView(self)
var calculatedIndex : Int?
for (index, item) in labels.enumerate() {
if item.frame.contains(location) {
calculatedIndex = index
}
if calculatedIndex != nil {
selectedIndex = calculatedIndex!
sendActionsForControlEvents(.ValueChanged)
}
}
return false
}
}
I can explain begin tracking method, the other one is researchable i think so
/*** beginTrackingWithTouch.. method to customize tracking. ***/
// Parameters : touch : this returns the touch that occurred at a certain point in the view. withEvent, returns the UIEvent
// associated with the touch.
// Return Type: Boolean.
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
let location = touch.locationInView(self) // This line returns the location of touch in the view. This location is in CGPoint.
var calculatedIndex : Int?
for (index, item) in labels.enumerate() { /// enumeration of an array gives you sequence type of integer and corresponding element type of the array.
if item.frame.contains(location) { /// so labels.enumerate returns the key value pairs like so : [(0, labelatIndex0), (1, labelatIndex1).. and so on.]
calculatedIndex = index /// here index is the key, and item is the value (label.)
// So for every label/index pair, you check whether the touch happened on the label by getting the frame of the label and checking if location is a part of the frame
/// You equate the index to calculatedIndex
}
// Now you if your calculated index is a valid number, you class, which extends UIControl, will call its method stating the change of value(sendActionsForControlEvents).
// This in turn, will send a message to all the targets that have been registered using addTarget:action:forControlEvents: method.
if calculatedIndex != nil {
selectedIndex = calculatedIndex!
sendActionsForControlEvents(.ValueChanged)
}
}
return false
}

Resources