[iOS] - UITextView

iOS 2020. 8. 2. 13:14
import Foundation
import SnapKit


class TestUITextViewVC: UIViewController {
    lazy var noB_TextView : UITextView = {
        let value : UITextView = UITextView()
        
        value.backgroundColor = UIColor.cyan
        value.text = "안녕하세요 No.B.Rain 입니다. 
                      지금 여기는 
                      https://no-b-rain.tistory.com/ 입니다."
        value.textColor = UIColor.red
        // 그림자를 넣고 싶다면 아래와 같이 농도를 설정
        value.layer.shadowOpacity = 0.5
        // Text 정렬 (왼쪽)
        value.textAlignment = NSTextAlignment.left
        value.font = UIFont.systemFont(ofSize: CGFloat(20))
                   //UIFont.systemFont(ofSize: UIFont.buttonFontSize)
                   //UIFont.systemFont(ofSize: UIFont.systemFontSize)
                   //UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)
                   //UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)
                   
        value.layer.masksToBounds = true
        //value.layer.cornerRadius = "높이" * 0.05 
        //(둥근 모서리는 생성될 때 높이 값을 주입해서 설정)
        
        // 테두리 설정
        value.layer.borderWidth = 1
        value.layer.borderColor = UIColor.black.cgColor
        
        // 자동 URL 유형 처리
        value.dataDetectorTypes = UIDataDetectorTypes.all
                                //UIDataDetectorTypes.address
                                //UIDataDetectorTypes.calendarEvent
                                //UIDataDetectorTypes.phoneNumber
                                //UIDataDetectorTypes.link
                                //UIDataDetectorTypes.flightNumber
        // 편집 모드에서는 위의 "자동 URL 유형 처리" 기능이 동작하지 않음.
        value.isEditable = false
        return value
    }()
    
    lazy var noB_Label : UILabel = {
        // Label 생성 => 가로 300 , 세로 300
        let value : UILabel = UILabel (frame : CGRect (x: 0 , y: 0 , width: 300 , height: 100 ))
        
        value.backgroundColor = UIColor.black
        value.text = "No.B.Rain 노비의 문서"
        value.textColor = UIColor.yellow
        // Text 정렬 (중앙)
        value.textAlignment = NSTextAlignment.center

        // 둥근 모서리 => 둥근 모서리는 컨탠츠 높이의 5%가 가장 적당하고 이쁨(개인적으로..)
        value.layer.masksToBounds = true
        value.layer.cornerRadius = 150 * 0.05

        // 그림자
        value.shadowColor = UIColor.black
        return value
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //UILabel를 view에 추가
        self.view.addSubview(noB_Label)
        //UITextView를 view에 추가
        self.view.addSubview(noB_TextView)
        
        
        //화면 중앙 배치
        noB_Label.snp.makeConstraints { (constraint) in
            constraint.center.equalTo(self.view)
        }
        
        
        let nH : CGFloat = noB_Label.frame.height
        noB_TextView.snp.makeConstraints { (constraint) in
            //noB_TextView의 top 위치를 noB_Label의 bottom dp margine 50을 설정
            constraint.top.equalTo(noB_Label.snp_bottomMargin).offset(50)
            //noB_TextView의 좌/우측 기준을 noB_Label보다 +/-50으로 설정
            constraint.left.equalTo(noB_Label.snp_leftMargin).offset(-50)
            constraint.right.equalTo(noB_Label.snp_rightMargin).offset(50)
            
            //noB_TextView의 넓이를 noB_Label의 넓이와 동일 하도록.
            /** constraint.width.equalTo(noB_Label) **/
            //noB_TextView의 높이를 100으로 설정
            constraint.height.equalTo(nH)
        }
        
        //둥근 모서리
        noB_TextView.layer.cornerRadius = nH * 0.05
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
}

'iOS' 카테고리의 다른 글

[iOS] - UILabel  (0) 2020.08.02
[iOS] - SnapKit : Layout 정리  (0) 2020.08.01
[iOS] - CocoaPods(코코아팟), Xcode의 Library 관리  (0) 2020.08.01
[iOS] - Storyboard와 SwiftUI 없이 Project 만들기  (0) 2020.07.31

설정

트랙백

댓글

[iOS] - UILabel

iOS 2020. 8. 2. 10:00
import Foundation
import SnapKit

class TestUILabelVC: UIViewController {

   lazy var noB_Label : UILabel = {
        // Label 생성 => 가로 300 , 세로 300
        let lbl : UILabel = UILabel (frame : CGRect (x: 0 , y: 0 , width: 300 , height: 300 ))
        
        lbl.backgroundColor = UIColor.black
        lbl.text = "No.B.Rain 노비의 문서"
        lbl.textColor = UIColor.yellow
        // Text 정렬 (중앙)
        lbl.textAlignment = NSTextAlignment.center

        // 둥근 모서리 => 둥근 모서리는 컨탠츠 높이의 5%가 가장 적당하고 이쁨(개인적으로..)
        lbl.layer.masksToBounds = true
        lbl.layer.cornerRadius = 150 * 0.05

        // 그림자
        lbl.shadowColor = UIColor.black
        return lbl
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //UILabel 화면에 추가
        self.view.addSubview(noB_Label)
        
        //화면 중앙 배치
        noB_Label.snp.makeConstraints { (constraint) in
            constraint.center.equalTo(self.view)
        }
    }
}

설정

트랙백

댓글

[iOS] - SnapKit : Layout 정리

iOS 2020. 8. 1. 13:54

● Subject : Auto Layout apply using the Snapkit library 

  • To do 
  1. SnapKit을 사용하여 아주 간단한 화면 배치를 해볼 것입니다.
  2. Safe Area 영역 구성
  3. SnapKit 화면 구성 팁
  • SnapKit - 기본 구성
import UIKit
import SnapKit

class MyMainView: UIViewController {

    lazy var myButtonCenter: UIButton = {
        let btn = UIButton()
        btn.setTitle("My Button(C) ", for: .normal)
        btn.backgroundColor = UIColor.red
        return btn
    }()
    
    lazy var myButtonTop: UIButton = {
        let btn = UIButton()
        btn.setTitle("My Button(T)", for: .normal)
        btn.backgroundColor = UIColor.blue
        return btn
    }()
    
    lazy var myButtonLeft: UIButton = {
        let btn = UIButton()
        btn.setTitle("My Button(L)", for: .normal)
        btn.backgroundColor = UIColor.green
        return btn
    }()
    
    lazy var myButtonRight: UIButton = {
        let btn = UIButton()
        btn.setTitle("My Button(R)", for: .normal)
        btn.backgroundColor = UIColor.yellow
        return btn
    }()
    
    lazy var myButtonBottom: UIButton = {
        let btn = UIButton()
        btn.setTitle("My Button(B)", for: .normal)
        btn.backgroundColor = UIColor.cyan
        return btn
    }()


   override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(myButtonCenter)
        view.addSubview(myButtonTop)
        view.addSubview(myButtonBottom)
        view.addSubview(myButtonLeft)
        view.addSubview(myButtonRight)
        
        
        myButtonCenter.snp.makeConstraints { (make) in
            make.center.equalTo(view)
        }
        
        myButtonTop.snp.makeConstraints { (make) in
            make.top.centerX.equalTo(view)
        }
        
        myButtonBottom.snp.makeConstraints { (make) in
            make.bottom.centerX.equalTo(view)
        }
        
        myButtonLeft.snp.makeConstraints { (make) in
            make.left.centerY.equalTo(view)
        }
        
        myButtonRight.snp.makeConstraints { (make) in
            make.right.centerY.equalTo(view)
        }
        
    }

}

- 실행화면.

뭔가 이상함.. safe area를 적용 하면 될것이라 함. 

  • SnapKit - safe area 영역  
import UIKit
import SnapKit
import Foundation

class MyMainView: UIViewController {

    let safetyArea: UIView = {
        let v = UIView()
        v.backgroundColor = .black
        return v
    }()
    
    lazy var myButtonCenter: UIButton = {
        let btn = UIButton()
        btn.setTitle("My Button(C) ", for: .normal)
        btn.backgroundColor = UIColor.red
        return btn
    }()
    
    lazy var myButtonTop: UIButton = {
        let btn = UIButton()
        btn.setTitle("My Button(T)", for: .normal)
        btn.backgroundColor = UIColor.blue
        return btn
    }()
    
    lazy var myButtonLeft: UIButton = {
        let btn = UIButton()
        btn.setTitle("My Button(L)", for: .normal)
        btn.backgroundColor = UIColor.green
        return btn
    }()
    
    lazy var myButtonRight: UIButton = {
        let btn = UIButton()
        btn.setTitle("My Button(R)", for: .normal)
        btn.backgroundColor = UIColor.yellow
        return btn
    }()
    
    lazy var myButtonBottom: UIButton = {
        let btn = UIButton()
        btn.setTitle("My Button(B)", for: .normal)
        btn.backgroundColor = UIColor.cyan
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setBaseView()
        setView()
    }
    
    
    
    func setBaseView(){
        safetyArea.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(safetyArea)
        if #available(iOS 11, *) {
            let guide = view.safeAreaLayoutGuide
            safetyArea.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
            safetyArea.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
            safetyArea.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
            safetyArea.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
            
        } else {
            safetyArea.topAnchor.constraint(equalTo: topLayoutGuide.topAnchor).isActive = true
            safetyArea.bottomAnchor.constraint(equalTo: bottomLayoutGuide.bottomAnchor).isActive = true
            safetyArea.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
            safetyArea.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        }
    }

    func setView() {
        safetyArea.addSubview(myButtonCenter)
        safetyArea.addSubview(myButtonTop)
        safetyArea.addSubview(myButtonBottom)
        safetyArea.addSubview(myButtonLeft)
        safetyArea.addSubview(myButtonRight)
        
        myButtonCenter.snp.makeConstraints { (make) in
            make.center.equalTo(safetyArea)
        }
        
        myButtonTop.snp.makeConstraints { (make) in
            make.top.centerX.equalTo(safetyArea)
        }
        
        myButtonBottom.snp.makeConstraints { (make) in
            make.bottom.centerX.equalTo(safetyArea)
        }
        
        myButtonLeft.snp.makeConstraints { (make) in
            make.left.centerY.equalTo(safetyArea)
        }
        
        myButtonRight.snp.makeConstraints { (make) in
            make.right.centerY.equalTo(safetyArea)
        }
    }
}

 - 실행화면

perfect. !!

  • SnapKit 화면 구성 팁
/*** 화면에 표현할 UILabel 2개 준비 ***/
   lazy var box_A: UILabel = {
        let lbl = UILabel()
        lbl.textColor = .black
        lbl.text = "*************************"
        lbl.backgroundColor = .blue
        lbl.textAlignment = .center
        return lbl
    }()
    
    lazy var box_B: UILabel = {
        let lbl = UILabel()
        lbl.textColor = .black
        lbl.text = "--------------------"
        lbl.backgroundColor = .red
        lbl.textAlignment = .center
        return lbl
    }()
    
/*** 기준(box_A)에 의해 (box_B)를 크기및 위치 조정  ***/ 
    func test_adjust_size() {
        self.view.addSubview(box_A)
        self.view.addSubview(box_B)
        
        box_A.snp.makeConstraints { (make) in
            make.center.equalTo(self.view)
        }
        
        box_B.snp.makeConstraints { (make) in
            make.size.equalTo(box_A)
            make.top.equalTo(box_A.snp_bottomMargin).offset(20)
            make.left.equalTo(box_A)
        }

    }
    
/*** edge test  ***/  
    func test_edges_View() {
        self.view.addSubview(box_A)
        self.view.addSubview(box_B)
        
        box_A.snp.makeConstraints { (make) in
            make.center.equalTo(self.view)
        }
        
        box_B.snp.makeConstraints { (make) in
            make.edges.equalTo(box_A)
            .inset(UIEdgeInsets(top: 10,left: 10,bottom: 10,right: 10))
        }
    }    

왼쪽 결과 :test_adjust_size() , 오른쪽 결과 :test_adjust_size() 

유용한 function 
!!  snp.updateConstraints : Constraint를 업데이트할 필요가 있을 때 

!! snp.remakeConstraints: Constraint를 지우고 다시 설정

 

'iOS' 카테고리의 다른 글

[iOS] - UITextView  (0) 2020.08.02
[iOS] - UILabel  (0) 2020.08.02
[iOS] - CocoaPods(코코아팟), Xcode의 Library 관리  (0) 2020.08.01
[iOS] - Storyboard와 SwiftUI 없이 Project 만들기  (0) 2020.07.31

설정

트랙백

댓글

[iOS] - CocoaPods(코코아팟), Xcode의 Library 관리

iOS 2020. 8. 1. 13:51

● 주제 : CocoaPods가 무엇인지 알고, 사용법을 익힙니다.

  • 할 일
  1. CocoaPods 이란?
  2. Cocoapods 사용법.
  • 내용
  • CocoaPods 이란? - https://cocoapods.org/ 에 가서 보면 "WHAT IS COCOAPODS"에 간단명료하게 설명을 합니다.                     CocoaPods는 Swift와 Objective-C Cocoa Project의 dependency를  management 하는 기능을 하며, 아주 많은 앱에서 사용 중이고 project의 확장을 아름답게 도와준다고 자랑..... 하고 있습니다.     ㅡ_ㅡ;;; 뭐 덧 붙일 내용이 없네요. ㅎㅎ
  • Cocoapods 사용법 - cocoapods 설치
$ sudo gem install cocoapods
  • Cocoapods 사용법 - 사용 

순서
1) "Podfile" 을 만들기 위해 프로젝트 폴더로 이동
2) "Podfile" 생성
3) "Podfile" 편집
4) vi 상의 "Podfile" 파일 내용 및 수정
5) "Podfile" 설치

$ cd "my-prject"
$ pod init
$ vi Podfile


# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target '프로젝트 명' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!
  
  ###'아래 부분에 필요한 라이브러리 추가 (SnapKit,AFNetworking,RealmSwift)'
  pod 'SnapKit', '~> 5.0.0'
  pod 'AFNetworking', '~> 3.0'
  pod 'RealmSwift' 
  ###'필요한 라이브러리 추가 끝'
  
  # Pods for 프로젝트 명

  target '프로젝트 명' do
    inherit! :search_paths
    # Pods for testing
  end

  target '프로젝트 명' do
    # Pods for testing
  end

end

** Podfile 편집

###'아래 부분에 필요한 라이브러리 추가 (SnapKit,AFNetworking,RealmSwift)'
pod 'SnapKit', '~> 5.0.0'
pod 'AFNetworking', '~> 3.0'
pod 'RealmSwift'
###'필요한 라이브러리 추가 끝'

** Podfile 설치

$ pod install 

SnapKit Library를 pod install 성공 했을 때 위와 같이 확인 할 수 있습니다. 

** Podfile 적용 후 Xcode loading file : "프로젝트명. xcworkspace" 파일로 프로젝트를 열 수 있습니다.

'iOS' 카테고리의 다른 글

[iOS] - UITextView  (0) 2020.08.02
[iOS] - UILabel  (0) 2020.08.02
[iOS] - SnapKit : Layout 정리  (0) 2020.08.01
[iOS] - Storyboard와 SwiftUI 없이 Project 만들기  (0) 2020.07.31

설정

트랙백

댓글

[iOS] - Storyboard와 SwiftUI 없이 Project 만들기

iOS 2020. 7. 31. 21:27

● 주제 : Storyboard를 사용하지 않고 소스만으로 프로젝트를 만들어 보려 합니다.

  • 왜 Storyboard 없이 소스만으로 프로젝트를 만들려고 할까?
  1. git과 같은 형상관리 툴을 사용해서 협업을 할 때 심심 찬 게 Storyboard의 영역에서 충돌(conflict)이 발생하고, 이를 해결하기 위한 시간적 비용도 많이 소비됩니다.
  2. 복잡한 Layout을 표현할 때 소스로 구현하면 제약조건(Constraint)을 쉽게 적용하고 추적할 수가 있습니다. 소스로 구현하다 보면, 자연스럽게 ViewController도 재사용을 하게 되고요.
  • 할 일
  1. 프로젝트 만들기
  2. sceneDelegate 삭제 (프로젝트에 등록된 정보와 소스파일 삭제)
  3. 새 ViewController 만들기 ("MyRootView.swift" , "MyRootView.xib" 생성과 두 파일과의 연결) 
  4. AppDelegate 수정 (앱의 기본 화면이 될 "MyRootView"와 UINavigationController를 등록)

 

  • 프로젝트 만들기 - 아래 그림과 같이 User Interface의 값은 "Storyboard"로 설정합니다.

  • sceneDelegate 등록 정보 삭제 - "Info.plist"의 Application Scene Manifest" 항목 삭제 -> "-" 버튼 눌러서 프로젝트에 등록된 기본 화면 정보를 삭제합니다.

  •  sceneDelegate 소스 파일 삭제 - 위 내용에 이어서 실제 "sceneDelegate.swift"파일을 삭제합니다.

  • 새 ViewController 만들기 : "MyRootView.swift" -  새 파일 만들기 메뉴 경로 "File -> New -> File..."로 이동하여"  "Swift File"을 선택하고, "Next"버튼을 누른 후 "MyRootView.swift 2)"처럼 Save as에 MyRootView와 같이 파일명을 입력 후 "Create" 버튼을 누릅니다.

 

"MyRootView.swift" 1)
"MyRootView.swift" 2)

  • 새 ViewController - "MyRootView.swift" 파일 작성
//UIKit 추가
import UIKit

import Foundation

//Class 생성과 UIViewController 상속
class MyRootView: UIViewController {
    
    //viewDidLoad 오버라이드 
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 실행시 초록색 화면이 보입니다. (메인화면을 잘 봐꿨는지 확인용.)
        self.view.backgroundColor = UIColor(red: 0, green: 1, blue: 0, alpha: 0.3)
    }
}
  • 새 ViewController 만들기 : "MyRootView.xib" - 새 파일 만들기 메뉴 경로 "File -> New -> File..."로 이동하여"  "View" 선택하고, "Next"버튼을 누른  "MyRootView.xib 2)"처럼 Save as에 MyRootView와 같이 파일명을 입력 후 "Create" 버튼을 누릅니다.

 

 "MyRootView.xib" 1)
"MyRootView.xib" 2)

  • 새 ViewController 만들기 : "MyRootView.xib의 File's Owner의 Custom Class에 MyRootView.swift 연결"

MyRootView.xib 파일 선택 -> File's Owner 선택 -> Custom class 에 "MyRootView" 입력
그림의 "View" icon을 우클릭 -> Referencing Outlets "+"를 File's Owner로 Drag 합니다.

  • AppDelegate 수정 - "UISceneSession Lifecycle"의 관련된 내용을 삭제합니다. 

      - 참고로, SwiftUI는 이전 버전과의 호환성이 없는 문제점이 있습니다. (단지 제 의견이다만,) 시간이 지나고 SwiftUI 가 조금 더 다듬어지고 유연해진다면 SwiftUI는 대중화될 것입니다. 하지만 하위 버전의 호환성을 고려하지 않고 개발하는 경우가 아니면 호환성을 고려해서 SwiftUI를 덜어 내는 것이 정신 건강상 좀 더 좋을 것 같습니다. ^^;

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, 
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    /** 여기부터 지움... (UISceneSession 관련 내용)
    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, 
                     configurationForConnecting connectingSceneSession: UISceneSession, 
                     options: UIScene.ConnectionOptions) -> 
                     UISceneConfiguration {
                      // Called when a new scene session is being created.
                      // Use this method to select a configuration to 
                      // create the new scene with.
		return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, 
                     didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, 
        // this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, 
        // as they will not return.
    }
    여기까지... (UISceneSession 관련 내용)
    */

}
  • AppDelegate 수정 - MyRootView와 UINavigationController 등록
import UIKit
import Foundation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    // rootViewController에 navigation 을 등록할 UIWindow. 
    var window: UIWindow?
    // 화면 이동과 화면 이력을 관리할 UINavigationController 추가.
    var navigation : UINavigationController? = nil
    // 앱이 시작 할 때 보여 줄 기본 화면 (이름을 MyRootView 로 정함.)
    var myRootView : MyRootView!

    func application(_ application: UIApplication, 
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        // 아래 내용 작성.
        myRootView = MyRootView()
        navigation = UINavigationController.init(rootViewController: myRootView)
                          
        // 상단 네비게이션바 숨김.                  
        navigation?.setNavigationBarHidden(true,animated: false) 
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = navigation
      
        return true
    }

    /** 여기부터 지움... (UISceneSession 관련 내용)
    // MARK: UISceneSession Lifecycle

 

  • 결과 화면 - 위 MyRootView의 배경색 설정이 적용된 ViewController로 적용이 되어서 실행되는 것을 확인할 수 있습니다.

 

*^^* 여기까지 읽어주신 독자님께 감사드립니다. iOS 개발을 배워 나가며 쓰는 글입니다. 글의 내용 중 틀린 내용이 있거나 부족한 점 있다면 귀뜸 부탁드립니다. 

다음 글은 Snapkit의 project 등록과 사용법 공부해 보겠습니다.

'iOS' 카테고리의 다른 글

[iOS] - UITextView  (0) 2020.08.02
[iOS] - UILabel  (0) 2020.08.02
[iOS] - SnapKit : Layout 정리  (0) 2020.08.01
[iOS] - CocoaPods(코코아팟), Xcode의 Library 관리  (0) 2020.08.01

설정

트랙백

댓글