How to display lists of strings in array for one UILabel on Storyboard like tablecell (swift) - swift

var comments: [String] = ["Good", "Great","Excellent","Cool"]
I would like to show comments within one UILabel (like tablecell), but I'm not sure it's possible. If possible, how can I achieve this.
I want to use UILabel as space for comments column.
example of image

If you want to add the array of those Strings to the single label then you can follow this approach:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var lblDynamic: UILabel!
let stringsArray = ["Good", "Great","Excellent","Cool"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
lblDynamic.text = stringsArray.joinWithSeparator("\n")
lblDynamic.numberOfLines = self.stringsArray.count + 1
lblDynamic.lineBreakMode = NSLineBreakMode.ByWordWrapping
}
}

Related

Enabling access to data and displaying that data on two different types of Views

I am accessing a Realm database to load values in my iOS app. The first one works fine. I have a UIViewController with UITextFields. The big picture is that i:
Define the outlets in the ViewController and connect them to the mainstoryboard UITextFields. There are three fields
I set up an array and load the results of the Realm query from a PersonData.swift data model. Three properties defined in the swift file.
In viewDidLoad I call the function to loadPersonData.
The first thing in the loadPersonData func is to put the realm.objects including three properties into the three fields that are defined by the Outlets at the top of the ViewController.
They load perfectly, are editable, and I can save the values of the data entry from the screen to the Realm database with a Realm modify. I can show you this code if you want to see it.
This is all working fine. Now my problem. My next View is a UITableViewController, with prototype cell, and three UILabels in each single cell row. This code has in the past used an Array for testing and that worked fine to load sample data back to the rows. I want to now read Realm data and scroll up and down with the three fields in each row. Later, when I select one,I will expose in another View all of the properties of that object called Year which is approximately 10 properties or UITextFields that can be edited.
I was told to build a subclass for the protype cell that will be a sub to the UITableViewCell.
class BYMyCell: UITableViewCell {
I put the Outlets for the three UILabels from the prototype cell into the BYMyCell.swift subclass. These outlets are connected to the UILabels defined in the prototype cell.
I saw one suggestion about putting the same outlets in the first businessYearViewController where all the row support functions were located. I was told to add the = nil to these outlets.
#IBOutlet weak var yearLabel: UILabel! = nil
#IBOutlet weak var descriptionLabel: UILabel! = nil
#IBOutlet weak var startingDateLabel: UILabel! = nil
Now when I try to move the Results of the Realm query from the three properties to the three Labels there appears to be nil in all the fields. I can see the data come into my businessYearViewController where I make the query, but I am having trouble putting the data into the Outlets in the BYMyCell.swift data model for exposure on the view/screen.
If I should post my two files, I will try to put them in a response. Thanks for your help. I'm pretty sure this has something to do with my lack of knowledge of processing TableViewController and prototype cell coordination. My rows are simple. One row, three labels. I will also have an add button at the top right corner and the ability to edit the fields in another View for data entry and changes.
Edited one hour later with information. This is my loadBusinessYear func.
func loadBusinessYearData() {
businessYearArray = realm.objects(YrData.self)
print(businessYearArray!.count)
print(businessYearArray?[0])
if businessYearArray!.count > 0 {
yearLabel.text = businessYearArray?[0].year
descriptionLabel.text = businessYearArray?[0].yearType
startingDateLabel.text = businessYearArray?[0].startingDate
} else {
yearLabel.text = "Sample Name"
descriptionLabel.text = "Sample .com"
startingDateLabel.text = "Sample Date"
}
}
The two print statements at the top give you the 1 for the count and the object properties as Optionals.
1
Optional(YrData {
ydID = 0;
year = 2020;
yearType = Business Open;
startingDate = 12/28/2019;
firstWeekEndDate = 01/03/2020;
lastWeekEndDate = 01/03/2021;
firstQtrTotal = 520;
secondQtrTotal = 520;
thirdQtrTotal = 520;
fourthQtrTotal = 520;
leapYearExtraWeek = 40;
yearContains53Weeks = 1;
laborReporting = List<LaborReportData> <0x600000a15290> (
);
expenseAccounting = List<ExpenseAccountData> <0x600000a15440> (
);
})
The data subclass is BYMyCell swift file.
import UIKit
class BYMyCell: UITableViewCell {
#IBOutlet weak var yearLabel: UILabel!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var startingDateLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}

UIButton inside table cell not changing attributes

I have a UIButton inside my cell together with an image and a text label. I manage to change the image and label programatically, but the UIButton does not seem to respond to anything except isHidden.
This is my code, the button that is not changing is followButton:
import UIKit
class ProfileTableCell: UITableViewCell {
#IBOutlet weak var name: UILabel!
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var followButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
self.profileImage.layer.borderWidth = 0.0;
self.profileImage.layer.cornerRadius = self.profileImage.frame.size.width/2;
self.profileImage.clipsToBounds = true
self.profileImage.image = UIImage(named: "belt")
self.name.text = "Bar Refaeli"
self.followButton.layer.borderColor = UIColor.black.cgColor
self.followButton.layer.borderWidth = 3.0;
self.followButton.layer.cornerRadius = self.frame.size.width/4
self.followButton.backgroundColor = UIColor.black
}
func setCell(image: UIImage, name: String){
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
The profileImage and name outlets change the appearance fine, like mentioned above.
I also tried to remove the button and bring it back in, clean xcode project, remove the outlet reference and connecting it again. Pretty frustrated by now.
I also tried to change the background color of the button through the storyboard, just for testing, and it does not change it! what does change is the titleLabel and the text color.
awakeFromNib()- Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file.
Given that, move your code to a view initiating method like viewDidLoad or viewDidAppear(_:)
Child objects that are attributes like textLabels act differently than child view objects.
Eventually I actually solved this by tossing the table view to the garbage and implementing the same needs using a collection view. there was no problem there..

Dynamically adding to NSStackView and Adding Scrolling Functionality

Like the title says, I am trying to dynamically add NSTextViews and NSImageViews to a NSStackView. First, I added a Scroll View using IB and that made a hierarchy of Bordered Scroll View -> Clip View -> Main View -> Stack View (Vertical). I want to be able to dynamically add views to the stack view and be able to scroll through them all. I used autolayout on the Bordered Scroll View.
The problem: I tested this by adding 100 NSTextViews and incrementing their y-positions to stack up on each other. But, I cannot scroll to the top. I have been trying to understand this for a couple days but I just cannot figure it out. I cannot scroll and see all the text views, but when I increase the window size I can see more of them. TIA! `
import Cocoa
class ViewController: NSViewController {
var xLoc = CGFloat(0)
var yLoc = CGFloat(0)
#IBOutlet weak var mainView: NSStackView!
#IBOutlet weak var belowMainView: NSStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
for index in 1...100 {
var txt = "Num: \(index)"
setup(text: txt)
}
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func setup(text: String){
let tempTextView = NSTextView(frame: NSMakeRect(xLoc, yLoc, 320, 10))
tempTextView.append(text)
tempTextView.isEditable = false
tempTextView.translatesAutoresizingMaskIntoConstraints = false
// mainView.addSubview(tempTextView)
belowMainView.addSubview(tempTextView)
yLoc += 20
}
}
// Adding an append function to textView functionality
extension NSTextView {
func append(_ string: String) {
self.textStorage?.append(NSAttributedString(string: string))
// Scrolls to end of document if it is out of view
self.scrollToEndOfDocument(nil)
}
}`

Set inputview for Searchbar - Swift

class TestViewController: UIViewController, UISearchBarDelegate {
#IBOutlet weak var mySearchBar: UISearchBar!
var myOwnInputView = UIView(frame: CGRectMake(100,100,50,50))
overide func viewDidLoad() {
mySearchBar.delegate = self
mySearchBar.inputView = myOwnInputView // errors - "Cannot assign to the result of this expression
}
}
I'm trying to assign a custom input view to my search bar, however based on apple documentation (-sorry could not find link anymore), for UISearchBar it seems to be a read-only value. Looking at this post, it appears that UISearchbar has multiple subviews and I need to get to the UITextField part in order to change the inputview. However, I'm not sufficiently familiar with Obj-C and my attempts to convert the code to Swift have not been successful.
This is the simplest way:
let searchTextField = searchBar.valueForKey("_searchField") as! UITextField
searchTextField.inputView = myOwnInputView
Found out that the textfield is a subview of a subview of UISearchbar.
Code to get to the textfield in swift:
var fakeView: UIView = UIView(frame: CGRectMake(100, 100, 50, 50))
#IBOutlet weak var searchBar: UISearchbar!
override func viewDidLoad() {
fakeView.backgroundColor = UIColor.redColor()
var c = 0
for v in (self.searchBar.subviews[0]).subviews {
c++
println("\(c).\(v)") //you should see two views - UISearchBarBackground and UISearcBarTextField
if let tf = v as? UITextField {
//do stuff to tf here.
//in my case, what I want is:
tf.inputView = fakeView
break
}
}
}}
Result of above code is no keyboard will show up when the searchbar text field is touched, just a red rectangle.
Note - credit goes to Matt Neuburg's "Programming iOS8: Dive Deep into Views, ViewControllers, and Frameworks (ISBN: 978-1491908730). Chapter 8 to be precise.

Setting a Border for TextView (Xcode 6.1)

I've tried finding the answer to this and every time it's assuming I know way too much. I'm a total beginner. I just created a new, blank application. I dragged the TextView to the storyboard. What do I do next to give it a border?
There is no code other than the default, autogenerated code at this point.
Here are the steps:
If you let Xcode create a project, go to the ViewController.swift file. Here you can create an outlet.
#IBOutlet var text : UITextField?
Now you can connect the text outlet to the textfield in the storyboard. You can do this by choosing the assistant editor. Than control drag a line from the outlet in the code to the textfield.
After the textfield is connected, you can add code to make a border in the viewDidLoad function.
class ViewController: UIViewController {
#IBOutlet var text : UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
text!.layer.borderWidth = 1
text!.layer.borderColor = UIColor.redColor().CGColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
In Swift 3 and Xcode 10,
tested and working in (swift 5 and code 12)
first, create an outlet of your text view
And In your viewdidload put these two lines
class ViewController: UIViewController {
#IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
self.textView.layer.borderColor = UIColor.lightGray.cgColor
self.textView.layer.borderWidth = 1
}
}