I have a UIScrollView with 1000 UIImages in it. These UIImages have a row and col attribute. How do I search the UIScrollView's UIImages for a specific row and col? (Then I will update the image) I am getting this error: For-in loop requires 'UIScrollView' to conform to 'Sequence'
Something like:
for eachImageView in MyUIScrollView! {
if eachImageView.row = searchrow {
if eachImageView.col = searchcol {
// do something
}
}
}
The MyUIScrollView subviews eachImageView row and col are just Int from a class:
class cellUIImageView: UIImageView {
var row: Int = 0
var col: Int = 0
...
First, a note: class names should begin upper-cased... use CellUIImageView instead of cellUIImageView.
Anyway...
You can find your view like this:
let v2 = scroll.subviews.filter {
($0 as? CellUIImageView)?.row == searchrow && ($0 as? CellUIImageView)?.col == searchcol
}
guard v2.count == 1, let foundView = v2.first as? CellUIImageView else {
print("CellUIImageView with row:", searchrow, "and col:", searchcol, "was not found!")
return
}
// do something with it, such as
foundView.image = replacementImage
Hi Good morning every one please any one to solve this issues
I had 4 images one password filed
here when user enter capital and small letter and I need to tick one image
again user enter enter number in textfield I need to tick another image
again user enter special character I need to tick another image
if user remove character based on that I need to deselect the image any one help to solve this issues
here is my code
#IBAction func textFieldEditingChanged(_ sender: Any) {
viewPasswordStrength.isHidden = false
if isValidated(passwordTextField.text!){
print("succ")
}
}
func isValidated(_ password: String) -> Bool {
var lowerCaseLetter: Bool = false
var upperCaseLetter: Bool = false
var digit: Bool = false
var specialCharacter: Bool = false
for char in password.unicodeScalars {
if !lowerCaseLetter {
lowerCaseLetter = CharacterSet.lowercaseLetters.contains(char)
}
if !upperCaseLetter {
upperCaseLetter = CharacterSet.uppercaseLetters.contains(char)
}
if !digit {
digit = CharacterSet.decimalDigits.contains(char)
}
if !specialCharacter {
specialCharacter = CharacterSet.punctuationCharacters.contains(char)
}
}
if ( lowerCaseLetter && upperCaseLetter) {
//do what u want
self.UpperCaseImageConditions_img.image = UIImage(named: "GreenTick")
return true
}
if (specialCharacter) {
//do what u want
self.SpecialCharacter_img.image = UIImage(named: "GreenTick")
return true
}
if ( digit) {
//do what u want
self.onenumberImageCondiotion_img.image = UIImage(named: "GreenTick")
return true
}
else {
self.UpperCaseImageConditions_img.image = UIImage(named: "redtick")
return false
}
}
here I cannot change the image based on the user enter the text in password filed
THANKS IN ADVANCE
I am using Storyboards and I'd like to have some labels which always show a given emoji at the start of the label.
I have the following code:
import UIKit
import CocoaLumberjack
class PITLabel: UILabel {
override public var text: String? {
set {
super.text = newValue?.prependedWithGenderEmoji()
DDLogDebug("🖌 set super.text: \(super.text ?? "🔴")")
}
get {
let newVal = super.text?.prependedWithGenderEmoji()
DDLogDebug("🖌 get super.text: \(newVal ?? "🔴")")
return newVal
}
}
override public var attributedText: NSAttributedString? {
set {
super.attributedText = newValue
DDLogDebug("🖌 set super.attributed: \(super.attributedText ?? NSAttributedString(string: "🔴"))")
}
get {
let genderString = super.attributedText?.string.prependedWithGenderEmoji()
let rangePointer = UnsafeMutablePointer<NSRange>.allocate(capacity: 8)
rangePointer.pointee = NSMakeRange(0, 1)
let originalAttributes = super.attributedText?.attributes(at: 0, effectiveRange: rangePointer)
let newAttributedString = NSAttributedString(string: genderString!, attributes: originalAttributes)
DDLogDebug("🖌 get super.attributed: \(newAttributedString)")
return newAttributedString
}
}
}
And I've set the labels to class PITLabel in the Storyboard.
When the app is run the following is present in the console output:
🖌 get super.text: 🙋♂️ PiT SETTINGS
🖌 get super.attributed: 🙋♂️ PiT SETTINGS{
NSColor = "UIExtendedSRGBColorSpace 0.0352941 0.498039 0.662745 1";
<snip>
}
This is as expected.
But in the UI of the app it does not show the emoji.
What am I missing?
Because you're actually not prepending it to the text. It should be:
override public var text: String? {
set {
let result = newValue.prependedWithGenderEmoji()
super.text = result
}
get {
return super.text
}
}
Setting the text in Interface Builder does not call the text setter that you override. You have to set it in the code.
yourPitLabel.text = "PiT SETTING
How can I check if a String (for example "apple") contains text that I typed in a UITextField (for example "p" or "pp").
If the String contains the UITextField's text, I want to print a message - for example: "apple contains pp".
You can achieve that like so
class youClass: NSObject {
var yourTextFieldName = UITextField()
func someMethod() {
var apple = "apple"
if apple.containsString(self.yourTextfieldName.text!) {
print("apple contains \(self.yourTextfieldName.text!)")
}
}
}
You could extend String:
extension String {
#discardableResult
func containsText(of textField: UITextField) -> Bool {
// Precondition
guard let text = textField.text else { return false }
let isContained = self.contains(text)
if isContained { print("\(self) contains \(text)") }
return isContained
}
}
Instead of just printing a result, it also returns a Bool indicating whether or not the textField's text was contained in the String. The #discardableResult attribute allows you to ignore the return value if you want to though, without generating a compiler warning.
You could also take a reversed approach, by extending UITextField:
extension UITextField {
#discardableResult
func textIsContained(in target: String) -> Bool {
// Precondition
guard let text = self.text else { return false }
let isContained = target.contains(text)
if isContained { print("\(target) contains \(text)") }
return isContained
}
}
You would use these methods as follows:
// Your `UITextField`
let textField = UITextField()
textField.text = "pp"
// String extension:
"apple".containsText(of: textField) // returns `true` and prints "apple contains pp"
// UITextField extension:
textField.textIsContained(in: "apple") // returns `true` and prints "apple contains pp"
This is an extension, not a duplicate, of How to check if a text field is empty or not in swift
The given answer,
#IBAction func Button(sender: AnyObject) {
if textField1.text != "" {
// textfield 1
}
}
does not work for me, i.e., the if-loop is triggered even when nothing is entered in the text field. (I have modified it from the original because I'm looking to trigger the code only when the field contains text).
The second answer
#IBAction func Button(sender: AnyObject) {
if !textField1.text.isEmpty{
}
}
comes much closer, but it accepts strings like " " as not empty. I could build something myself, but is there a function that will check if a string contains something other than whitespace?
This answer was last revised for Swift 5.2 and iOS 13.5 SDK.
You can trim whitespace characters from your string and check if it's empty:
if !textField1.text.trimmingCharacters(in: .whitespaces).isEmpty {
// string contains non-whitespace characters
}
You can also use .whitespacesAndNewlines to remove newline characters too.
Below is the extension I wrote that works nicely, especially for those that come from a .NET background:
extension String {
func isEmptyOrWhitespace() -> Bool {
if(self.isEmpty) {
return true
}
return (self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "")
}
}
Swift 4.2
Extension for String is empty or whitespace
extension String {
func isEmptyOrWhitespace() -> Bool {
// Check empty string
if self.isEmpty {
return true
}
// Trim and check empty string
return (self.trimmingCharacters(in: .whitespaces) == "")
}
}
The original poster's code is checking text on a textfield which is optional. So he will need some code to check optional strings. So let's create a function to handle that too:
Extension for Optional String is nil, empty or whitespace
extension Optional where Wrapped == String {
func isEmptyOrWhitespace() -> Bool {
// Check nil
guard let this = self else { return true }
// Check empty string
if this.isEmpty {
return true
}
// Trim and check empty string
return (this.trimmingCharacters(in: .whitespaces) == "")
}
}
akashivskyy answer in Swift 3.0:
let whitespaceSet = CharacterSet.whitespaces
if !str.trimmingCharacters(in: whitespaceSet).isEmpty {
// string contains non-whitespace characters
}
extension StringProtocol where Index == String.Index {
var isEmptyField: Bool {
return trimmingCharacters(in: .whitespaces) == ""
}
}
if yourTextField.text.isEmptyField {
// Field is empty
} else {
// Field is NOT empty
}
Answer in swift 4:
extension String {
func isEmptyOrWhitespace() -> Bool {
if(self.isEmpty) {
return true
}
return (self.trimmingCharacters(in: NSCharacterSet.whitespaces) == "")
}
}
Answer in Swift 3.0
if stringValue.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty
{}
Answer in Swift 3.*, considers newlines, tabs
extension String {
var containsNonWhitespace: Bool {
return !self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
}
Answer with a picture in case you need a demo
// MY FUNCTIONS
private func checkMandatoryFields(){
//CHECK EMPTY OR SPACES ONLY FIELDS
if let type = typeOutle.text, let name = nameOutlet.text, let address = addressOutlet.text, type.trimmingCharacters(in: .whitespaces).isEmpty || name.trimmingCharacters(in: .whitespaces).isEmpty || address.trimmingCharacters(in: .whitespaces).isEmpty {
print("Mandatory fields are: ")
errorDisplay(error: "Mandatory fields are: Type, Name, Address.")
return
}
}
swift 4.2
#IBAction func checkSendButton(_ sender: UITextField) {
if((sender.text?.count)! > 0 && !(sender.text!.trimmingCharacters(in: .whitespaces)).isEmpty){
self.sendButton.isEnabled = true
}
else{
self.sendButton.isEnabled = false
}
}
Method
func trim() -> String {
return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
}
Use
if textField.text.trim().count == 0 {
// Do your stuff
}